Anna
Anna

Reputation: 571

Printf() after fork() and conditional being printed only once?

So I am trying to learn the fork() call, I am honestly confused on how this child process and parent process works. Here is part of the code:

int main()
{
    pid_t pid;

    pid = fork();

    if (pid == 0) {
        value = ChildProcess(value);
        return 0;
    }
    else if (pid > 0) {
        value = ParentProcess(value);
    }

    printf("\nThe value is %d",value);
    return 0;
}

Now the output should give me parent value and child value, and since there is no wait() call either parent value or child value can be printed first. But what I am confused is, why does the printf statement only being printed once?? Shouldn't it being printed twice since the fork call basically created a duplicated program??

Upvotes: 0

Views: 241

Answers (1)

Tom Tanner
Tom Tanner

Reputation: 9354

because you return from the child process after calling ChildProcess, so don't go through the printf

Upvotes: 2

Related Questions