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