0
我在編程一個計數器,它使用flocks來運行計數器程序的多個實例。程序從文件讀取和寫入,增加文件中的值。當我運行多個實例時,該文件包含正確的值,但是當我運行一次文件(./count5)時,文件中的值停在3000,但由於while循環結束於500,所以它停止在500。任何幫助,將不勝感激。在一個程序的多個實例中使用flocks
while(cnt < 500)
{
struct flock lock = {F_WRLCK, SEEK_SET, 0, 0, 0};
lock.l_pid = getpid();
fd = open("num3", O_RDWR | O_APPEND);
if (fcntl (fd, F_SETLKW, &lock) != -1) /* Set the lock to wait while another instance is already running */
{
fp1 = fopen("num3", "a+"); /*Read from file*/
while(fgets(buff, 255, fp1) != NULL); /*Moves to last line of file*/
i = atoi(buff); /*Convert buff to int*/
i++; /*Increment the value*/
sprintf(temp,"%d\n", i); /*Prints the incremented value to temp*/
fputs(temp, fp1);
fclose(fp1);
lock.l_type = F_UNLCK;
fcntl(fd, F_SETLK, &lock);
close(fd);
cnt++; /*Increment counter*/
}
}
您似乎正在將值'i'寫入文件。所以寫入的值取決於文件中已有的值。 – 2014-10-09 22:31:48