1.在Linux中并没有exec函数,而是有6个以exec开头的函数族,下面列举了exec函数族的6个函数成员的函数原型。
int execl(const char *path, const char *arg, ...)
int execv(const char *path, char *const argv[])
int execle(const char *path, const char *arg, ..., char *const envp[])
int execve(const char *path, char *const argv[], char *const envp[])
int execlp(const char *file, const char *arg, ...)
int execvp(const char *file, char *const argv[])
2.exec函数族的使用场景
在Linux中使用exec函数族主要有以下两种情况:
1. 当进程认为自己不能再为系统和用户做出任何贡献时,就可以调用任何exec 函数族让自己重生。
2. 如果一个进程想执行另一个程序,那么它就可以调用fork函数新建一个进程,然后调用任何一个exec函数使子进程重生。
3.execl的简单使用
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
pid_t pid;
pid = fork();
if(pid < 0){
printf("fork is error\n");
return -1;
}
if(pid > 0){
printf("this is father pid,pid = %d\n",getpid());
}
if(pid == 0){
printf("this is child pid,pid = %d\n",getpid());
printf("this is child pid's father pid = %d\n",getppid());
execl("/bin/ls","ls","-al",NULL);//第一个参数为可执行文件路径,第二个参数为文件名,第三个为执行参数,第四个为NULL
exit(1);//执行成功退出
}
return 0;
}