Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork in background don't work correct [duplicate]

Tags:

c

linux

I run this prog. in foreground and background:

int main()    
{
    int pid;
    printf("App Start pid=%d!\n",getpid());

    while(1) {
        pid=fork();
        if(pid==0) {
            printf("Child\n\n");
            exit(0);
        }
        else if(pid>0) {
            printf("Parent\n");
        }    
        sleep(1);
    }
}

in foreground:

$ ./fork

result is:

App Start pid=1360!    
Parent    
Child    
Parent    
Child    
...

in background:

$./fork > out.txt &
$cat out.txt    
App Start pid=1368!    
Child    
App Start pid=1368!    
Parent    
Child    
App Start pid=1368!    
Parent    
Parent    
Child    
...

Why does the app 'restart' in background? I don't understand what happening. How can i make fork to work correctly in background app? Thanks

like image 325
pic32mz Avatar asked Dec 19 '25 11:12

pic32mz


1 Answers

This has to do with the output buffers: newly created process are writing over and over what their parent already printed. Notice that the message does not change, i.e.: it is always App Start pid=1368!.

Place fflush(stdout) after the first call to printf():

printf("App Start pid=%d!\n",getpid());
fflush(stdout);

This way the output buffer will be flushed before creating the children processes.


Note that by starting the fork program without redirecting stdout (i.e.: $ ./fork), stdout is line-buffered by default. For that reason, a flush of stdout is already performed every time it receives a new-line character.

like image 69
ネロク・ゴ Avatar answered Dec 21 '25 00:12

ネロク・ゴ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!