kaushalpranav
kaushalpranav

Reputation: 2174

Definition of fork() in the program

I have studied that fork() call creates a new process from where it is called in the program.

But in the following two programs, which are very similar, it shows different behavior. Why is this?

Program 1:

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

int main(int argc, char* argv[])
{
    printf("Start %d ", getpid()) ; 
    pid_t pid = fork() ;
    if (pid > 0)
        printf("Parent %d ", getpid()) ; 
    if (pid == 0)
        printf("Child %d ", getpid()) ;
    return 0 ; 
}

Output for this is:

Start 1104 Parent 1104 Start 1104 Child 1105

Program 2:

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

int main(int argc, char* argv[])
{
    printf("Start %d \n", getpid()) ; 
    pid_t pid = fork() ;
    if (pid > 0)
        printf("Parent %d \n", getpid()) ; 
    if (pid == 0)
        printf("Child %d \n", getpid()) ;
    return 0 ; 
}

Output for this is:

Start 1126 
Child 1127 
Parent 1126 

Just including "\n" changes the output. What causes this?

Upvotes: 0

Views: 44

Answers (1)

David Schwartz
David Schwartz

Reputation: 182753

If you're going to use a stream in both the parent and the child, you need to flush it before you fork. Otherwise, whatever's left in the buffer will get flushed twice, once by the parent and once by the child.

Also, you should not return from main in both the parent and the child. If you do, any atexit handlers will run twice. This has caused bugs with security implications in the past. Either the parent or the child should either call _exit or successfully call one of the exec functions.

Upvotes: 5

Related Questions