gpt4 book ai didi

c - 将集群与程序的多个实例一起使用

转载 作者:行者123 更新时间:2023-11-30 17:27:45 25 4
gpt4 key购买 nike

我正在用c语言编写一个计数器,它利用flocks来运行计数器程序的多个实例。该程序从文件中读取和写入,从而增加文件中的值。当我运行多个实例时,该文件包含正确的值,但是当我运行该文件一次 (./count5) 时,文件中的值在 3000 处停止,但它应该在 500 处停止,因为 while 循环在 500 处结束。任何帮助将不胜感激。

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写入文件。因此写入的值取决于文件中已有的内容。 ——格雷格·休吉尔

关于c - 将集群与程序的多个实例一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26288967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com