What happens if I call fork() inside main? [duplicate]

[亡魂溺海] 提交于 2019-12-23 21:45:01

问题


Simple piece of code:

#include <stdio.h>
#include <string.h>

main()
{
     printf("Process");
     fork();
     fork();
     return 0;
}

From my understanding of fork(), after this code executes we will have 3 child processes and 1 parent process. Also whenever we call fork() the execution should start from the statement immediately after the fork() statement. Hence according to me "Process" should be printed only once. But in my output Process is being printed 4 times. How is that possible?


回答1:


Because the standard output is line buffered by default, when you call fork(), the output buffer is inherited by all the children processes.

There are several different ways to change this behavior:

Add a new line character at the end:

printf("Process\n");

or call fflush() to flush the output:

printf("Process");
fflush(stdout);

or change standard output to not buffered using setbuf() or setvbuf():

setbuf(stdout, NULL);
printf("Process");

Using either way, you'll see the output only once.

Note: see @Dvaid Schwartz's answer for the bug with calling atexit() multiple times in your code.




回答2:


Your program has a bug. All the children return from main, causing atexit handlers to run four times. The children should call _exit.

Here's how your code should look:

#include <stdio.h> 
#include <string.h>
#include <unistd.h>

main()
{
     int is_child = 0; 
     printf("Process");

     if (fork() == 0) 
        is_child = 1; 

     if (fork() == 0) 
        is_child = 1;

     if (is_child)
        _exit(0);

     return 0;
}


来源:https://stackoverflow.com/questions/22008504/what-happens-if-i-call-fork-inside-main

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!