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

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -