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?
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 theforkis different than what the parent sees.So yes, you are correct, once you hit the
if, or theelse ifor theelseyou’re not going to get into another branch of the code, in a single process’ execution. You’re seeing theelse ifand theelsebecause you have two processes running.note how the
pid1‘s are different, becausegetpid()is returning which process is running that code, and you can see you have two different processes, one picks theelse ifthe other picks theelse.