为什么我的孩子有时只从文件中打印特定行?

问题描述 投票:0回答:1

我正在尝试使用父进程读取一行并从子进程读取另一行来从文件中读取特定行。简单文本文件具有以下内容:“这是第一行\ n”,这是第二行\ n“,等等。

但是,我发现当我多次执行程序时,我的孩子并不总是从文件中打印该行。 printf(“ Entering child \ n”)总是得到执行,表明我能够很好地输入子进程。

为什么这仅在某些时候有效?

int main() {
FILE* fptr = fopen("my_text.txt","r");

int stat;
pid_t pid;
int count = 0;
if(fptr != NULL) {
    char line[256];
    fflush(stdout);
    if((pid = fork()) < 0) {
        fprintf(stderr, "fork error: %s\n",strerror(errno));
    }
    else if(pid == 0) {
        printf("entering child\n");
        int lineNumber = 2; // read the second line
        while (fgets(line, sizeof(line), fptr) != NULL) { // loop until we get to desired line
            if (count == lineNumber) {

                printf("CHILD read: %s", line);

                fflush(stdout);
                rewind(fptr);
                break;
            } else {
                count++;
            }
        }
        exit(0); // exit child process

    } else { // parent process

        int lineNumber = 1; 
        while (fgets(line, sizeof(line), fptr) != NULL) { // loop until desired line
            if (count == lineNumber) {
                printf("PARENT read: %s", line);
                fflush(stdout);  
                rewind(fptr);
                break;
            } else {
                count++;
            }
        }
        wait(&stat); // reap the child process
    }
    fclose(fptr);
} else {
    printf("File Does not exist\n");
    exit(0);
}

return 0; }   

根据上面的代码,我有时会打印“这是第二行”(来自父级)和“这是第三行”(来自子级),有时只打印“这是第二行”。目标是同时打印两者。

c parent-child stdout file-read multiple-processes
1个回答
0
投票

这两个进程共享打开文件描述,这意味着它们都共享文件偏移量因此,您有一个race condition,因为他们读取了文件[[concurrently。有两种明显的解决方法:

    使用某些IPC机制进行同步
  • 在分叉之后,在
  • 每个
进程中打开文件。[其他高级方法例如是用pread读取文件,还是用mmap在分叉之前或之后读取文件...
© www.soinside.com 2019 - 2024. All rights reserved.