Search code examples
clinuxfork

why does my console look like it performed a command after using fork() to create 3 children?


okay so either I am having this weird bug on my end or it is just a bug on my end and it is nothing that I need to worry about. In any case I am working on an assignment I need to fork 3 times, and i have some quick dummy code here:

for(int x = 0; x < 3; x++) {
    procID = fork();
    if (procID == 0) {
        sleep(3);
        printf("child process: \n");
        exit(0);
    }

}

here is the output i want/need:

y@y:~/Desktop/playground$ ./a
child process
child process
child process
y@y:~/Desktop/playground$

But here is the output that I am getting:

y@y:~/Desktop/playground$ gcc a.c -o a -lm
y@y:~/Desktop/playground$ ./a
y@y:~/Desktop/playground$ child process
child process
child process

the line containing the problem is this one: y@y:~/Desktop/playground$ child process

why does it automatically make it look as if i input the command y@y:~/Desktop/playground$ child process into the console. I was digging into it and trying to fix this on my own but evidently i cannot do this by myself. I understand that once the last parent quits then the "y@y:~/Desktop/playground$" is placed into the console, is there anything i can do to force the parent to wait until the children have finished executing? or is there something else at play here?


Solution

  • why does it automatically make it look as if i input the command [..]

    It doesn't. What you see is your shell prompt.

    The reason is you haven't called wait(2) from the parent process for all child processes to exit. So when the parent exits before one or more children, you'd observe that behaviour.

    is there anything i can do to force the parent to wait until the children have finished executing?

    Call wait(NULL); in a loop after the for loop so that the parent waits for all children:

    while (wait(NULL) > 0);