首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Linux C编程-历程介绍2-exec函数

2013-03-06 
Linux C编程--进程介绍2--exec函数exec函数族fork()函数是用于创建一个子进程,该子进程几乎拷贝了父进程的

Linux C编程--进程介绍2--exec函数
exec函数族

fork()函数是用于创建一个子进程,该子进程几乎拷贝了父进程的全部内容,但是,这个新创建的进程如何执行呢?这个exec函数族就提供了一个在进程中启动另一个程序执行的方法。 

exec函数族包括6个函数:

int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, const char *envp[]);
int execv(const char *path, const char *argv[]);
int execve(const char *path, const char *argv[], const char *envp[];
int execvp(const char *file, const char *argv[]);


参数说明:

execl的第一个参数是包括路径的可执行文件,后面是列表参数,列表的第一个为命令path,接 着为参数列表,最后必须以NULL结束。
execlp的第一个参数可以使用相对路径或者绝对路径。
execle,最后包括指向一个自定义环境变量列表的指针,此列表必须以NULL结束。
execv,v表示path后面接收的是一个向量,即指向一个参数列表的指针,注意这个列表的最后 一项必须为NULL。
execve,path后面接收一个参数列表向量,并可以指定一个环境变量列表向量。
execvp,第一个参数可以使用相对路径或者绝对路径,v表示后面接收一个参数列表向量。

exec被调用时会替换调用它的进程的代码段和数据段(但是文件描述符不变),直接返回到调用它的进程的父进程,如果出错,返回-1并设置errno。


下面给出两个例子

1.这是一个非常简单的程序,只是为了说明exec的使用

#include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>int main(int argc, char *argv[]){int fd;int stat,pid;struct stat stbuf;time_t old_time=0;if(argc!=3){fprintf(stderr,"Usage: %s watchfile copyfile \n", argv[0]);return 1;}if((fd=open(argv[1],O_RDONLY))==-1){fprintf(stderr,"Watchfile: %s can't open \n", argv[1]);return 2;}fstat(fd, &stbuf);old_time=stbuf.st_mtime;for(;;){fstat(fd, &stbuf);if(old_time!=stbuf.st_mtime){while((pid=fork())==-1);if(pid==0){execl("/bin/cp","/bin/cp",argv[1],argv[2],0);return 3;}wait(&stat);old_time=stbuf.st_mtime;}elsesleep(30);}}

wait(&stat);
old_time=stbuf.st_mtime;

这两句的功能是:

父进程调用另一个系统函数wait等待子进程终止


进程被while((pid=fork())==-1);这条语句中断

热点排行