Chinaunix首页 | 论坛 | 博客
  • 博客访问: 127361
  • 博文数量: 19
  • 博客积分: 508
  • 博客等级: 下士
  • 技术积分: 306
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-11 21:04
文章分类

全部博文(19)

文章存档

2011年(16)

2009年(3)

我的朋友

分类: LINUX

2011-07-15 13:14:02

Outline 

- 1.exec函数族

- 2.测试

=================================================================================================

1. exec函数族
exec函数通常与fork函数一起使用,在fork子进程以后,立刻调用exec。
exec函数的作用是将调用进程完全替换为一个新的进程,即将由fork产生的子进程独立成一个新的进程,该进程执行由exec函数第一个参数指定的程序文件。

  1. int execl( char *pathname,char *arg0,char *arg1,...,char *argn,NULL)
  2. int execle( char *pathname,char *arg0,char *arg1,...,char *argn,NULL,char *envp[])
  3. int execlp( char *filename,char *arg0,char *arg1,...,NULL)

  4. int execv( char *pathname,char *argv[])
  5. int execve( char *pathname,char *argv[],char *envp[])
  6. int execvp( char *filename,char *argv[])
path和filename的区别就是:/path/program 和 program,后者在环境变量PATH中搜索program,当然,后者也可以直接写成/path/program

2. 测试
exec.c
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>

  4. int main()
  5. {
  6.     pid_t pid;

  7.     printf("parent process: pid is %d\n", getpid());
  8.     fflush(stdout);

  9.     pid = fork();
  10.     if (pid < 0)
  11.         printf("fork failed.\n");
  12.     else if (pid == 0) {
  13.         printf("child process: pid is %d, ppid is %d\n", getpid(), getppid());
  14.         execl("./test", (char *)0);
  15.     }

  16.     sleep(1);
  17.     printf("over\n");
  18.     return 0;
  19. }
test.c
  1. #include <stdio.h>
  2. #include <unistd.h>

  3. int main()
  4. {
  5.     printf("after execl, child process: pid is %d, ppid is %d\n", getpid(), getppid());
  6.     return 0;
  7. }
输出:
  1. parent process: pid is 12305
  2. child process: pid is 12306, ppid is 12305
  3. after execl, child process: pid is 12306, ppid is 12305
  4. over

阅读(1354) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~