Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working of fork() in linux gcc [duplicate]

Tags:

c

linux

fork

gcc

fork() creates a new process and the child process starts to execute from the current state of the parent process.

This is the thing I know about fork() in Linux.

So, accordingly the following code:

int main() {   printf("Hi");   fork();   return 0; } 

needs to print "Hi" only once as per the above.

But on executing the above in Linux, compiled with gcc, it prints "Hi" twice.

Can someone explain to me what is happening actually on using fork() and if I have understood the working of fork() properly?

like image 361
Mor Eru Avatar asked Aug 18 '10 14:08

Mor Eru


People also ask

What does fork () do in Linux?

fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling process is referred to as the parent process. The child process and the parent process run in separate memory spaces.

Does fork copy all memory?

What fork() does is the following: It creates a new process which is a copy of the calling process. That means that it copies the caller's memory (code, globals, heap and stack), registers, and open files.

What happens when fork () is called?

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call.

Does fork double memory?

Save this answer. Show activity on this post. fork() duplicates the entire process. The only difference is in the return value of the fork() call itself -- in the parent it returns the child's PID, in the child it returns 0 .


1 Answers

(Incorporating some explanation from a comment by user @Jack) When you print something to the "Standard Output" stdout (computer monitor usually, although you can redirect it to a file), it gets stored in temporary buffer initially.

Both sides of the fork inherit the unflushed buffer, so when each side of the fork hits the return statement and ends, it gets flushed twice.

Before you fork, you should fflush(stdout); which will flush the buffer so that the child doesn't inherit it.

stdout to the screen (as opposed to when you're redirecting it to a file) is actually buffered by line ends, so if you'd done printf("Hi\n"); you wouldn't have had this problem because it would have flushed the buffer itself.

like image 146
Paul Tomblin Avatar answered Oct 13 '22 04:10

Paul Tomblin