o ## exec族函数
为什么使用exec族函数?
让一个进程要执行另一个不同的程序。在fork创建一个新进程后,调用exec族函数来让新进程执行其他程序。
exec族函数:
execl, execlp, execle, execv, execvp, execvpe ,调用失败时返回-1,并从调用点继续往下执行。
exec族函数原型
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...);
int execv(const char *path, char *const argv[]);
int execlp(const char *file, const char *arg, ...);
int execvp(const char *file, char *const argv[]);
int execle(const char *path, const char *arg,..., char * const envp[]);
int execvpe(const char *file, char *const argv[],char *const envp[]);
path:可执行文件的路径名字,arg:可执行程序所带的参数。file:可执行文件路径 名,或者PATH环境变量。
测试代码:调用execl让子进程执行date获取时间
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
int cnt =0;
pid = vfork();
if(pid == 0){
while(1){
cnt++;
printf("this is childpro\n");
sleep(1);
if(cnt == 5){
printf("child quit,wait to get time\n");
exit(0);
}
}
}
if(pid > 0){
printf("start to get time\n");
if(execl("/bin/date","date",NULL,NULL) == -1)
{
printf("execl error\n");
perror("why");//打印失败原因
}
printf("execl failed\n");
}
return 0;
}
运行结果: