execution of if/else if/else with a fork()

c, fork, operating-system

Solution

You should read up on fork(). Once you hit a `fork()` statement a second process is started, it has a copy of everything the parent process has but it can run a separate execution, and the return it sees from the `fork` is different than what the parent sees.

 int main()
 {
   pid_t pid, pid1;
                   <--- up to here you have one process running
   pid = fork();   <--- when this returns you have two processes:
                          parent has pid = child's pid               child has pid = 0


   if(pid<0)       <--- child and parent both check this, it's not true so they move on
   {
     ....
   }
   else if(pid == 0)<--- this is true for the child, not the parent
   {
     ....           <--- child will now execute this code
   }
   else             <-- nothing else was true for the parent so it sees this
     ....           <-- and executes this code

So yes, you are correct, once you hit the `if`, or the `else if` or the `else` you're not going to get into another branch of the code, in a single process’ execution. You’re seeing the `else if` and the `else` because you have two processes running.

note how the `pid1`'s are different, because `getpid()` is returning which process is running that code, and you can see you have two different processes, one picks the `else if` the other picks the `else`.

Problem

I have tried implementing an os program. Here is the code: ``` #include<sys/types.h> #include<stdio.h> #include<unistd.h> int main() { pid_t pid, pid1; pid = fork(); if(pid<0) { fprintf(stderr,"Fork Failed"); return 1; } else if(pid == 0) /* child process */ { pid1 = getpid(); printf("child: pid = %d\n",pid); printf("child: pid1 = %d\n",pid1); } else /* parent process */ { pid1 = getpid(); printf("parent: pid = %d\n",pid); printf("parent: pid1 = %d\n",pid1); } return 0; } ``` and its o/p: ``` parent: pid = 1836 parent: pid1 = 1835 child: pid = 0 child: pid1 = 1836 ``` can somebody explain me how is it working , i.e. the sequence of the execution for the `if`/`else-if`/`else` statements written in the code. I would think once the `else if` condition becomes true then `else` part is not executed, however here it has executed the parent process part i.e. `else` part and then the child part ..... how come?

Original source