Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Questions on fork() [duplicate]

Tags:

c

fork

I am trying to understand fork(), and so I put together the following example:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

void main()
{
   if(fork()==0)
   {
      printf("2");

      if(fork()==0)
      {
          printf("4");
      }
      else
      {
          printf("3");
      }
   } 
   else
   {
      printf("1");
   }
}

When I was tracing this on paper, I drew the following sketch:

enter image description here

So I believe the output should be 1234. However, when I run this code, the output is 12324. Why is that? Where is my mistake?

Update:

After reading the comments, it was suggested to do any of the following

  1. Add \n to each printf statement
  2. OR: Add fflush(stdout); after each printf statement
  3. OR: Add setbuf(stdout, NULL); <---- this is what I ended-up doing :)

After updating my code, the output was indeed 1234.

like image 604
lucidgold Avatar asked Nov 06 '14 18:11

lucidgold


People also ask

Does fork () duplicate all threads?

A fork() duplicates all the threads of a process. The problem with this is that fork() in a process where threads work with external resources may corrupt those resources (e.g., writing duplicate records to a file) because neither thread may know that the fork() has occurred.

Does fork () duplicate only the calling thread or all threads?

The fork subroutine duplicates the parent process, but duplicates only the calling thread; the child process is a single-threaded process. The calling thread of the parent process becomes the initial thread of the child process; it may not be the initial thread of the parent process.

Does fork duplicate 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.

Does fork duplicate data?

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 . Most operating systems optimize this, using a technique called copy on write.


1 Answers

printf() output is usually line-buffered. So when you fork(), the new processes gets the copy of the buffer as well. When the process exits, the whole buffer is flushed (or anytime it's flushed in the code or whenever the buffer becomes full). Hence, you see a copy of printf's output one more time.

1) You can flush it after each printf() call by using fflush(stdout);

2) or using \n for example:

  printf("2\n");

Another way is to disable the buffering with:

setbuf(stdout, NULL);
like image 191
P.P Avatar answered Oct 14 '22 08:10

P.P