vfork,fork,exec函数的区别

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; 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值