2
   if (pid==0)
   {
     //child
   }
   else
   {
    //parent
     ...
   }

Why is the 'else' part necessary? isn't it implied that we are in the parent ?

user3687001
  • 335
  • 1
  • 3
  • 12
  • Remember `fork()` can fail. If you don't test for failure you will run the parent code alone. `if (pid == -1) { perror("fork"); } else { /* ... */ }` – pmg Jun 05 '14 at 11:53
  • 1
    Personally, I use a switch statement with the 3 options: *-1* means failure; *0* means we are in the child; *default* means we are in the parent. – jmlemetayer Jun 05 '14 at 13:01

2 Answers2

7

isn't it implied that we are in the parent ?

No. After a fork() call, there are two processes that run from exactly that same point in the code. Only one is the parent. The code you put in the else block is run only by the parent, just as the code inside the if block is run only by the child. Code that comes after the entire if/else statement is executed by both the child and the parent.

Caleb
  • 124,013
  • 19
  • 183
  • 272
0

It's not necessary unless you want to do something with both the original(parent) and the new(child) processes.

if((pid = fork()) == 0){
    //child
}else{
    //parent
}
MGHandy
  • 363
  • 1
  • 3
  • 11