c - About vfork() system call? -


#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 parent %d\nmy child %d\n",getpid(),child_pid);        wait(null);    }     else    {        printf("hey child %d\nmy parent %d\n",getpid(),getppid());        execl("/bin/echo","echo","hello",null);        exit(0);    }    return 0; } 

output:

 hey child 4  parent 3  hey parent 3  child 4  hello 

my question : why "hello" printed after execution of parent process? have started learning vfork(). please me this?

after parent process executed, goes wait(null); blocks parent process until child process calls execl() or exit.

therefore child process when parent blocked calling execl() , hello being printed in end of output.

#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 parent %d\nmy child %d\n",getpid(),child_pid);    wait(null);  }   else  {    printf("hey child %d\nmy parent %d\n",getpid(),getppid());    execl("/bin/echo","echo","hello",null);    exit(0);   }  return 0;   } 

if remove execl() child process go exit(0) , hello wont printed.

also, after execl() being executed creating new process code write after execl() wont executed. according man page:-

the exec() family of functions replaces current process image new process image. functions described in manual page front-ends execve(2). (see manual page execve(2) further details replacement of current process image.)


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -