exec函数族
int
execl(const char *path, const char *arg0, ... /*, (char *)0 */);
int
execle(const char *path, const char *arg0, ...
/*, (char *)0, char *const envp[] */);
int
execlp(const char *file, const char *arg0, ... /*, (char *)0 */);
int
execv(const char *path, char *const argv[]);
int
execvp(const char *file, char *const argv[]);
int
execvP(const char *file, const char *search_path, char *const argv[]);
- execl, 可以指定路径进行运行自己的程序
- execlp, 可以通过自己的环境变量,运行系统程序
- execvp, 可以通过传入数组的方式
execlp使用案例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int main(int agrc, char *argv[])
{
pid_t pid = fork();
if (pid==-1){
perror("fork error");
exit(1);
}else if(pid==0){ // 子进程
// 找到NULL之后就结束
// execlp("ls", "-l", "-d", "-h", NULL); // 错误的写法
execlp("ls", "ls", "-l", "-d", "-h", NULL);
// 下面的代码只有在出错的时候才会执行
perror("exec error");
exit(1);
}else if (pid>0){ // 父进程
printf("I'm parent: %d
");
}
return 0;
}
execl的使用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int main(int agrc, char *argv[])
{
pid_t pid = fork();
if (pid==-1){
perror("fork error");
exit(1);
}else if(pid==0){ // 子进程
// 找到NULL之后就结束
// execlp("ls", "-l", "-d", "-h", NULL); // 错误的写法
//execlp("ls", "ls", "-l", "-d", "-h", NULL);
execl("./a.out", "a.out", "-l", "-d", "-h", NULL);
// 下面的代码只有在出错的时候才会执行
perror("exec error");
exit(1);
}else if (pid>0){ // 父进程
printf("I'm parent: %d
");
}
return 0;
}
exec函数族的一般规律
- exec函数一旦调用成功,就执行新的程序,不返回。只有失败才返回,错误值为-1,通常直接在exec函数后直接调用perror()和exit(),不需要进行if判断
- l(list) 命令行参数列表
- p(path) 搜索file的时候使用的path变量
- v(vector)使用命令行参数数组
- e (environment) 使用环境变量数组,不使用进程原有的环境变量,设置新添加的环境变量
- 其实只有execve 才是真正的系统调用,其他的exec函数族都是调用的execve