Feng Yu
Feng Yu

Reputation: 369

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

Upvotes: 1

Views: 97

Answers (2)

geert3
geert3

Reputation: 7341

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.

Upvotes: 0

Daniel Daranas
Daniel Daranas

Reputation: 22644

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.

Upvotes: 4

Related Questions