简体   繁体   English

fork()新进程并写入子进程和父进程的文件

[英]Fork() new process and write to files for child and parent processes

I'm new to fork(), parent and child processes and have some difficulty understanding the logic behind the code that I wrote, but did not perform what I expected. 我是fork(),父进程和子进程的新手,并且难以理解我编写的代码背后的逻辑,但没有达到我的预期。 Here is what I have: 这是我有的:

 int main (int argc, char** argv)
 {
     FILE *fp_parent;
     FILE *fp_child;

     fp_parent = fopen ("parent.out","w");
     fp_child = fopen ("child.out","w");

     int test_pid;
     printf ("GET HERE\n");

     fprintf (fp_parent,"Begin\n"); // MY CONCERN

     for (int i = 0; i < 1; i++) //for simplicity, just fork 1 process.
     {                          // but i want to fork more processes later
        test_pid = fork();
        if(test_pid < 0)
        {
          printf ("ERROR fork\n");
          exit (0);
        }
        else if(test_pid == 0) // CHILD
        {
          fprintf(fp_child,"child\n");
          break;
        }
        else //PARENT
        {
          fprintf(fp_parent,"parent\n");
        }
     }
     fclose(fp_parent);
     fclose(fp_child);
 }

So the output of above code is: 所以上面代码的输出是:

 to stdout: GET HERE

 in parent.out:

 Begin

 parent

 Begin

 in child.out:

 child

My main concern is that I don't quite understand why "Begin" get written to parent.out twice. 我主要担心的是我不太明白为什么“Begin”会被写入parent.out两次。 If I remove the for loop completely, then only one "Begin" is written which is expected. 如果我完全删除for循环,则只写入一个“Begin”,这是预期的。

So I think that it's because of the fork() and definitely I miss or don't understand some logic behind it. 所以我认为这是因为fork()而且我肯定想念或者不理解它背后的一些逻辑。 Could you guys please help me explain? 你能帮我解释一下吗?

My plan to be able to write something before the for loop in parent.out and write something during the for loop in parent.out. 我的计划是能够在parent.out中的for循环之前写一些东西,并在parent.out中的for循环期间写一些东西。 Child process will write to child.out. 子进程将写入child.out。

In C, the input/output operations using FILE structure are buffered at the level of user process. 在C中,使用FILE结构的输入/输出操作在用户进程级别进行缓冲。 In your case, the output you have written to fp_parent was not actually written onto the disk and was kept in a local buffer at the moment of fork . 在您的情况下,您写入fp_parent的输出实际上并未写入磁盘,并且在fork时保存在本地缓冲区中。 The fork creates a copy of the whole process including the buffer containing Begin and this is why it appears twice in your file. fork创建整个过程的副本,包括包含Begin的缓冲区,这就是它在文件中出现两次的原因。 Try to put fflush(fp_parent); 尝试把fflush(fp_parent); before the fork . fork之前。 This will flush the buffer and the dirty line will disappear from the file. 这将刷新缓冲区,脏线将从文件中消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM