Chinaunix首页 | 论坛 | 博客
  • 博客访问: 503506
  • 博文数量: 81
  • 博客积分: 7010
  • 博客等级: 少将
  • 技术积分: 1500
  • 用 户 组: 普通用户
  • 注册时间: 2005-12-15 10:51
文章分类

全部博文(81)

文章存档

2011年(1)

2009年(22)

2008年(58)

我的朋友

分类: C/C++

2008-12-31 13:42:44

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  
  2. #include  
  3. #include  
  4. #include  
  5. /* Spawn a child process running a new program. PROGRAM is the name 
  6.    of the program to run; the path will be searched for this program. 
  7.    ARG_LIST is a NULL-terminated list of character strings to be 
  8.    passed as the program's argument list. Returns  the process ID of 
  9.    the spawned process.  */ 
  10. int spawn (char* program, char** arg_list) 
  11. {
  12.   pid_t child_pid; 
  13.   /* Duplicate this process. */ 
  14.   child_pid = fork (); 
  15.   if (child_pid != 0) 
  16.     /* This is the parent process. */ 
  17.     return child_pid; 
  18.   else {
  19.     /* Now execute PROGRAM, searching for it in the path.  */ 
  20.     execvp (program,  arg_list); 
  21.     /* The execvp  function returns only if an error occurs.  */ 
  22.     fprintf (stderr,  "an error occurred in execvp\n"); 
  23.     abort (); 
  24.   } 
  25. int main () 
  26. {
  27.   /*  The argument list to pass to the "ls" command.  */ 
  28.   char* arg_list[] = {
  29.     "ls",     /* argv[0], the name of the program.  */ 
  30.     "-l"
  31.     "/"
  32.     NULL      /* The argument list must end with a NULL.  */ 
  33.   }; 
  34.   /* Spawn a child process running the "ls" command. Ignore the 
  35.      returned child process ID.  */ 
  36.   spawn ("ls", arg_list); 
  37.   printf ("done with main program\n"); 
  38.   return 0; 
阅读(2312) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~