Linux系统环境下fork函数是用于创建一个子进程,该子进程几乎是父进程的副本,而有时我们希望子进程去执行另外的程序,exec函数族就提供了一个在进程中启动另一个程序执行的方法。
它可以根据指定的文件名或目录名找到可执行文件,并用它来取代原调用进程的数据段、代码段和堆栈段,在执行完之后,原调用进程的内容除了进程号外,其他全部被新程序的内容替换了。另外,这里的可执行文件既可以是二进制文件,也可以是Linux下任何可执行脚本文件。
实际上,在Linux中并没有exec函数,而是有6个以exec开头的函数族,下表列举了exec函数族的6个成员函数的语法。
一、 exec函数语法
#include <unistd.h> extern char **environ; int execl(const char *path, const char *arg, ... /* (char *) NULL */); int execlp(const char *file, const char *arg, ... /* (char *) NULL */); int execle(const char *path, const char *arg, ... /*, (char *) NULL, char * const envp[] */); int execv(const char *path, char *const argv[]); int execvp(const char *file, char *const argv[]); int execvpe(const char *file, char *const argv[], char *const envp[]);
二、 exec函数示例
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main(void) { pid_t pid; if((pid = fork()) < 0) { perror("fork() error!\n"); exit(1); } else if(pid == 0) { if(execl("echoall", "echoall", "hello world", "beijing forum", (char *)NULL) < 0) { perror("execl() error!\n"); exit(1); } exit(0); } if(waitpid(pid, NULL, 0) < 0) { perror("waitpid() error!\n"); } exit(0); }
#include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { for(int i=0; i<argc; i++) { printf("%d:\t%s\n", i, argv[i]); } return 0; }
三、 运行结果
[ycxie@fedora Workspace]$ gcc echoall.c -o echoall -Wall [ycxie@fedora Workspace]$ gcc exec_demo.c -o exec_demo -Wall [ycxie@fedora Workspace]$ ./exec_demo 0: echoall 1: hello world 2: beijing forum