3

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

pic32mz
  • 31
  • 1

1 Answers1

4

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.

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • Interesting. Note The amount of times "parent" is printed increases. – kabanus Aug 28 '17 at 10:08
  • 3
    Correct answer, might want to add why it works without redirection ... (`stdout` line-buffered by default) –  Aug 28 '17 at 10:09