天天看点

vfork()系统调用-创建子进程,阻塞父进程

vfork():

The vfork() function is the same as fork() except that it does not make a copy of the address space. The memory is shared reducing the overhead of spawning a new process with a unique copy of all the memory. This is typically used when using fork() to exec() a process and terminate. The vfork() function also executes the child process first and resumes the parent process when the child terminates.

Example:

  1 #include<stdio.h>

  2 #include<unistd.h>

  3 #include<stdlib.h>

  4 int globalVariable = 2;

  5 int main(){

  6     char *sIdentifier;

  7     int iStackVariable = 20;

  8

  9     pid_t pID = vfork();

 10

 11     if( pID == 0 ) {   

 12         //Code only executed by child process

 13         sIdentifier = "Child Process: ";

 14         globalVariable++;                      

 15         iStackVariable++;                      

 16         printf( " %s ", sIdentifier );                                                             

 17         printf( " Global variable: %d", globalVariable );              

 18                                                                        

 19         printf( " Stack variable: %d/n", iStackVariable );                     

 20                                                                                

 21         _exit(0);                                                                  

 22                                                                                    

 23     } else if ( pID < 0 ) {                                                                    

 24         printf( "Failed to fork!/n" );                                                         

 25         exit(1);

 26         //Throw exception                                                                              

 27     } else {

 28         //Code only executed by parent process

 29         sIdentifier = "Parent Process: ";    

 30     }  

 31    

 32     //Code executed by parent. 

 33     printf( " %s ", sIdentifier );

 34     printf( " Global variable: %d ", globalVariable );

 35     printf( " Stack variable: %d/n", iStackVariable );

 36 }  

[email protected]:~/Documents/Linux C Programming/Process/vfork$ gcc vfork.c

explo[email protected]:~/Documents/Linux C Programming/Process/vfork$ ./a.out

 Child Process:   Global variable: 3 Stack variable: 21

 Parent Process:   Global variable: 3  Stack variable: 21

Note: The child process executed first, updated the variables which are shared between the processes and NOT unique, and then the parent process executes using variables which the child has updated.

[Potential Pitfall] : A deadlock condition may occur if the child process does not terminate, the parent process will not proceed.

Man Pages:

  • vfork - create a child process and block parent
  • _exit - - terminate the current process