|
|

楼主 |
发表于 2006-4-12 21:21:25
|
显示全部楼层
我写了段代码, 但不知道怎么锁文件, 用fcntl和semaphore都试了, 都有问题
大侠们帮帮忙啊...
/////////////////////
// test1.c
// gcc -o test1 test1.c
// ./test1
//////////////////////////////////////
/// how to lock file when writing? ///
//////////////////////////////////////
#include <unistd.h>
#include <stdio.h>
#include <sys/fcntl.h>
#include <sys/wait.h>
#define NPID 10
/////????????????
int mklock ()
{
// i don't know how to implement that...
return 0;
}
/////?????????????
int unlock ()
{
// i don't know how to implement that...
return 0;
}
int DoSth (int a)
{
printf ("%ld is doing!!\n", getpid());
sleep (1);
return a*a;
}
int SaveToFile (char *filename, int nResult)
{
int fd;
char buf[10];
FILE *fp;
if ((fp = fopen(filename, "a")) == NULL) {
printf ("fopen %s for append error\n", filename);
return -1;
}
fprintf (fp, "%d ", nResult);
fclose(fp);
return 0;
}
int FileToArray(char *filename, int *arr)
{
int nResult;
int nCnt = 0;
FILE *fp;
if ((fp = fopen(filename, "r")) == NULL) {
printf ("fopen %s for read error\n", filename);
return -1;
}
while (!feof(fp)) {
fscanf (fp, "%d ", &nResult);
arr[nCnt] = nResult;
nCnt++;
printf ("%d ", nResult);
}
fclose(fp);
return 0;
}
int main ()
{
pid_t pid1;
int n1, i;
char filename[10];
int nArr[NPID];
FILE *fp;
int status;
sprintf (filename, "%ld.file", getpid());
printf ("%s created!!\n", filename);
if ((fp = fopen(filename, "w")) == NULL) {
printf ("create %s error\n", filename);
return -1;
}
fclose (fp);
for (i=0; i<NPID; i++) {
if ( (pid1 = fork()) < 0)
return -1;
if (pid1 == 0) {
pid1 = getpid();
n1 = DoSth (36+i);
//////////????????///////////////////////////
mklock();
SaveToFile(filename, n1);
unlock();
//////////????????//////////////////////////
return 0;
}
}
wait (&status);
sleep (1);
FileToArray(filename, nArr);
printf("================ %ld ==============\n", getpid());
for (i=0, n1=0; i<NPID; i++) {
n1 += nArr;
printf ("pid[%d] = %d\n", i, nArr);
}
printf ("total = %d\n", n1);
return 0;
} |
|