vfork,fork,exec函数的区别

来源:互联网 发布:部落冲突兵营升级数据 编辑:程序博客网 时间:2024/05/11 00:15
vfork用于创建一个新进程,而该新进程的目的是exec一个新进程,
vfork和fork一样都创建一个子进程,但是它并不将父进程的地址空间
完全复制到子进程中,因为子进程会立即调用exec,于是也就不会存放该地址空间。
。不过在子进程中调用exec或exit之前,他在父进程的空间中运行。


vfork和fork之间的另一个区别是: vfork保证子进程先运行,在她调用exec或exit之后
父进程才可能被调度运行。如果在调用这两个函数之前子进程依赖于父进程的进一步动作
,则会导致死锁。


用fork函数创建子进程后,子进程往往要调用一种exec函数以执行另一个程序,
当进程调用一种exec函数时,该进程完全由新程序代换,而新程序则从其main函数
开始执行,因为调用exec并不创建新进程,所以前后的进程id 并未改变,exec只是用
另一个新程序替换了当前进程的正文,数据,堆和栈段。  

Listing 3.4 (fork-exec.c) Using fork and exec Together
  1. #include <stdio.h> 
  2. #include <stdlib.h> 
  3. #include <sys/types.h> 
  4. #include <unistd.h> 
  5.  
  6. /* Spawn a child process running a new program. PROGRAM is the name 
  7.    of the program to run; the path will be searched for this program. 
  8.    ARG_LIST is a NULL-terminated list of character strings to be 
  9.    passed as the program's argument list. Returns  the process ID of 
  10.    the spawned process.  */ 
  11.  
  12. int spawn (char* program, char** arg_list) 
  13. {
  14.   pid_t child_pid; 
  15.  
  16.   /* Duplicate this process. */ 
  17.   child_pid = fork (); 
  18.   if (child_pid != 0) 
  19.     /* This is the parent process. */ 
  20.     return child_pid; 
  21.   else {
  22.     /* Now execute PROGRAM, searching for it in the path.  */ 
  23.     execvp (program,  arg_list); 
  24.     /* The execvp  function returns only if an error occurs.  */ 
  25.     fprintf (stderr,  "an error occurred in execvp/n"); 
  26.     abort (); 
  27.   } 
  28.  
  29. int main () 
  30. {
  31.   /*  The argument list to pass to the "ls" command.  */ 
  32.   char* arg_list[] = {
  33.     "ls",     /* argv[0], the name of the program.  */ 
  34.     "-l"
  35.     "/"
  36.     NULL      /* The argument list must end with a NULL.  */ 
  37.   }; 
  38.  
  39.   /* Spawn a child process running the "ls" command. Ignore the 
  40.      returned child process ID.  */ 
  41.   spawn ("ls", arg_list); 
  42.  
  43.   printf ("done with main program/n"); 
  44.  
  45.   return 0; 

原创粉丝点击