Sunday, September 14, 2014

Unix Prog: Clone Process -- vfork

1. vfork

vfork is used to clone a new process "WITHOUT" copying the parent process's address space. Any operation done by child process will take place at process's address space.

vfork is normally used to create a new process to run "exec" directly, since it will be much faster without copying parent process's data heap stack etc.

System Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/unistd.h  
 ......  
 /* Clone the calling process, but without copying the whole address space.  
   The calling process is suspended until the new process exits or is  
   replaced by a call to `execve'. Return -1 for errors, 0 to the new process,  
   and the process ID of the new process to the old process. */  
 extern __pid_t vfork (void) __THROW;  
 ......  

2. Example
proc.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
   
 int globval = 8;  
   
 int main(int argc, char* argv[])  
 {  
  int var;  
  pid_t pid;  
   
  var = 88;  
  printf("before vfork: \n");  
  if((pid = vfork()) < 0) {  
   printf("vfork error!\n");  
   exit(1);  
  }  
  else if (pid == 0) {  
   // At child process, it change the value of globval and var  
   // which exists in parent process's address space. So at parent  
   // process, the value will be changed as well. And before child  
   // process exit, parent process will keep sleeping.  
   globval++;  
   var++;  
   // If calling exit(0) in child process, it may close the standard
   // I/O stream, which also belongs to parent process, it may cause
   // parent process not be able to output content anymore.
   _exit(0);  
  }  
   
  printf("pid = %d, glob = %d, var = %d\n", getpid(), globval, var);  
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./proc.out  
 before vfork:  
 pid = 5456, glob = 9, var = 89  

No comments:

Post a Comment