user11913526
user11913526

Reputation:

Why parent print 2 times with fork in c

I'm learning fork() and I try to do a little program who print the child before the parent. It works but the parents print 2 times and I don't understand why.

Expected output :

4 5 6
1 2 3

Real output :

4 5 6
1 2 3
1 2 3

Here is my code :

int main (int argc, char** argv) {

    int childPid = fork();
    if (childPid == 0){
        printf("4 5 6\n");
    }

    wait(NULL);

    printf("1 2 3\n");
    exit(0);

}

Upvotes: 0

Views: 59

Answers (1)

Alex
Alex

Reputation: 357

The line printf("1 2 3\n"); will be executed by both parent a child. The child will confront the wait(NULL); line but will skip it since it has no childs and will print "1 2 3" and then it will exit. Meanwhile, the parent would receive the termination status of the child and will continue execution by printing "1 2 3" as well and exiting. In order to make it work properly, edit it accordingly:

int main (int argc, char** argv) {

    int childPid = fork();
    if (childPid == 0){
        printf("4 5 6\n");
        exit(0);
    }

    wait(NULL);

    printf("1 2 3\n");
    exit(0);

}

Upvotes: 1

Related Questions