Home > Enterprise >  Why child_1 will print before parent?
Why child_1 will print before parent?

Time:10-05

I have a C code that a parent process will fork() a child process:

int main(){
    pid_t child_1;
    child_1 = fork();
    if (child_1 > 0){
        printf("Parent: (PID %d)\n", getpid());
        wait(NULL);
    }
    else if (child_1 == 0){
        printf("child: %d", getpid());
    }
}

And the output is:

Parent: (PID 1234)
child: 1235

But if I removed the \n in the printf of parent, the output would become:

child: 1235Parent: (PID 1234)

I'm not sure why and I've tried on different OS and the output is the same. Thanks in advance.

CodePudding user response:

printf is line buffered. Which means it won't actually output until a newline is encountered or an explicit flush is done (such as when the process exits). So in your case removing the newline changes when the parent process actually outputs. Since the parent waits for the child to exit it means the parent flush will occur after the child has outputted.

  • Related