Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forking a process with C

Tags:

c

fork

I'm following this guide about fork() but something isn't clear for me.

Both processes will start their execution at the next statement following the fork() call. In this case, both processes will start their execution at the assignment statement as shown below: enter image description here

According to this sentence, this script

printf("before ");
fork();
printf("after ");

should print this: (Because child process will start from printf("after"))

before after after

but it is printing this instead:

before after before after

So did the child process start from the 1st line of the file? Can you tell me what's wrong with my code? Did I misunderstood that sentence?

EDIT

Script compiled and executed on OS X

like image 942
Eray Avatar asked Dec 13 '14 22:12

Eray


1 Answers

When you create a new process, it 'inherits' all the variables of the original process - thus all the buffers as well. Since "before" wasn't flushed yet and is still in the buffer, the child process will as well contain this string in the buffer and print it. Therefore you have to call fflush(stdout); before forking the process.

like image 168
Philipp Murry Avatar answered Oct 02 '22 16:10

Philipp Murry