#include <stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
pid_t child_pid = vfork();
if(child_pid < 0)
{
printf("vfork() error\n");
exit(-1);
}
if(child_pid != 0)
{
printf("Hey I am parent %d\nMy child is %d\n",getpid(),child_pid);
wait(NULL);
}
else
{
printf("Hey I am child %d\nMy parent is %d\n",getpid(),getppid());
execl("/bin/echo","echo","hello",NULL);
exit(0);
}
return 0;
}
output:
Hey I am child 4
My parent is 3
Hey I am parent 3
My child is 4
hello
My question : Why is "hello" printed after the execution of parent process? I have started learning about vfork(). Could anyone please help me with this?
After the parent process is executed, it goes to
wait(NULL);
which blocks the parent process until the child process callsexecl()
orexit
.Therefore the child process when the parent is blocked is calling the
execl()
and thushello
is being printed in the end of the output.If you remove
execl()
the child process will go to theexit(0)
andhello
wont be printed.Also, after
execl()
is being executed it is creating a new process thus any code you write afterexecl()
wont be executed. According to the man page:-