The code looks something like this
int main() {
printf("Starting process id is %d\t", getpid());
if (fork() == 0) {
fork();
} else {
fork();
fork();
exit(0);
}
printf("%d\t", getpid());
}
For the most part the outputs behave as expected where tracing. That is if we start with id n
we get n+1
and n+5
being printed. However when I print the starting process id it gets printed 5 times and I am not sure why. Any help would be appreciated
Output from a sample run looks like this
Starting process id is 27252 pc@pc-VirtualBox:~/Desktop$ Starting porcess id is 27252 Starting porcess id is 27252 Starting porcess id is 27252 27253 Starting porcess id is 27252 Starting process id is 27252 27257
However I would have expected to see
Staring process id is 27252 27253 27257
Your initial printf
doesn't end in a newline, and by default stdout
connected to a terminal is line buffered. Thus, when you fork
, the stdout
buffer isn't empty, and when flushed by each child process on exit
, it flushes the same data left in the buffer that it inherited.
To fix, do the following:
fflush(stdout)
before fork
ing_exit
, not exit
(this can prevent buffers from being flushed, though it's implementation dependent so you can't make guarantees, but it also blocks atexit
functions from being executed in the child process, which is usually the desired behavior)tcflush
to clear the buffered output prior to _exit
-ing.