Reputation: 793
main() {
fork();
fork();
printf("Hello world\n");
}
In the above program, the parent process spawns a child process. The child process in turn spawns a grandchild process. After executing this program i get the following output.
Macintosh:unix NightFury$ ./a.out
Hello world
Hello world
Hello world
Macintosh:unix NightFury$ Hello world
Why doesn't the output come as a single process output ? yes there should be 4 "Hello world" to be printed, but why is the last one printed as a separate process ?
Upvotes: 3
Views: 455
Reputation: 4185
They actually are printed as one but the parent process died and therefore the shell prints the "Macintosh:unix NightFury$" line and the the last remaining child-process prints its line afterwards. You should actually be able try this by adding a line in which you ask the parent process to wait until every child died, then there shouldn't be that line.
Upvotes: 1
Reputation: 992995
The shell waits for the first process to end, and then prints the shell prompt again. You've got three other processes running, and that time two of them wrote their output before the shell prompt appeared, and one wrote its output after. Things may not happen in this exact order every time you run your program - sometimes you might get the shell prompt back sooner or later than this example.
This is how you can write programs that keep running in the "background".
Upvotes: 4