简体   繁体   中英

Confusion about output of fork calls

Consider the output of the below program:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void main()
{
    pid_t pid;
    int a = 5;
    pid = fork();
    if (pid == 0)
        printf("This is the son process, a = %d\n", --a);
    else
        printf("This is the dad process, a = %d\n", ++a);
}

The output that I expected is:

This is the son process, a = 4;
This is the dad process, a = 6;

But I got the output as:

This is the son process, a = 4

So why the parent process did not execute the printf ? How can i get the output i want?

Update:

Just now I tried once more, output like this:

$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
$ This is the son process, a = 4

Now there is still a problem: why is there a $ between two lines of output?

I think the expected output should be like this:

$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
This is the son process, a = 4

I can't figure out why $ is there.

More details:

gcc version: gcc 4.8.2  
OS: ubuntu 14.04

You need to check the "fork failed" condition. When fork() returns -1, an error happened. This is part of the semantics of the function, so if you omit it, you will get incorrect results.

See an example which takes into account the possibility of fork failing here .

See a discussion of why fork could fail in this related question .

The $ is just the prompt that is displaying in between the process output. Because the child runs "detached" from the parent, the parent may return to the shell before the child has finished. So the prompt is printed, then the child's output. If you would redirect all output to a file, the $ will not be in there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM