//same program different code
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int pid;
pid=fork();
if(pid<0)
{
printf("\n Error ");
exit(1);
}
else if(pid==0)
{
printf("\n Hello I am the child process ");
printf("\n My pid is %d ",getpid());
exit(0);
}
else
{
printf("\n Hello I am the parent process ");
printf("\n My actual pid is %d \n ",getpid());
exit(1);
}
}
I tried this , I hope its correct .
But I am not satisfied with the output .
The output is :
Hello I am the parent process
My actual pid is 4287
ashu@ashu-VirtualWorld:~/Desktop/4thSemester/testprep$
Hello I am the child process
My pid is 4288
Please help me I cant understand its output , I want the child process to occur first and then parent process . Also , when the execution ends the control is transferred to the program , so to return to terminal I have to use ctrl+c , I want that after the execution of the program ends the control transfers to the terminal .
The thing with parallel processes is that they don't map well to the idea of "happening first"; they're running in parallel.
Of course, you can change the odds by having a delay in the code for the parent, before the print-outs.
Not at all sure what you mean by "the control is transferred to the program"; since both processes will hit exit()
very quickly after having printed their messages, there should be no program left to transfer control to.
Note that you don't need to use exit()
from main()
, it should end with a plain old return
since its return type is int
.