当我们需要在子进程中去执行其他的程序的时候,我们就需要用到exec系列函数
#include <unistd.h>
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
exec函数族有六个但是我们重点需要掌握的主要有以下两个:
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
l,p,v,e的含义
参数 | 含义 |
---|---|
p | 系统的的PATH环境 |
v | 命令行数组 |
e | 使用的环境变量数组 |
l | 命令行列表 ,命令行以NULL作为结束标志 |
exec函数使用的注意事项:
1.调用成功不会返回,调用失败返回-1
2.根据指定文件名找到可执行文件,并用它来调用进程的内容
案例1
execlp函数,使用execlp函数在子进程中显示当前日期
/*
* 使用execlp函数调用date
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid =fork(); //利用fork先创建一个子进程
if(pid<0)
{
perror("fork error");
exit(1);
}else if(pid==0){ //子进程
execlp("date","date",NULL); //这里的第一个date代表命令的名称,第二个date代表argv[0]
perror("execlp error"); //如果execlp调用成功的话,那么一下两行就不会执行了
exit(1);
}else if(pid>0){ //父进程
sleep(1);//让子进程先执行完
printf("I am the parent process,my id is %d\n",getpid());
}
return 0;
}
运行结果:
2020年 12月 04日 星期五 00:46:32 CST
I am the parent process,my id is 1028426
案例2
execl函数,使用execl在子进程中调用我们自己写的函数
1.下面是我自己写的一个小函数,接下来我要在子进程中执行这个函数
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("I am execl\n");
return 0;
}
2.execl完整代码
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid=fork();
if(pid==-1)
{
perror("fork error");
exit(1);
}else if(pid==0){ //子进程
execl("./execl_test","./execl_test",NULL);
perror("exec error");
exit(1);
}else if(pid>0){ //父进程
sleep(1);
printf("I am the father,my id id %d\n",getpid());
}
return 0;
}
运行结果:
I am execl
I am the father,my id id 1032591