介绍一下 exec函数族,那exec函数族到底是什么呢? exec函数族里面 有那些成员呢?
先看个视频了解一下
看完视频之后,我们来具体的介绍一下这个exec函数族
一.exec函数族
fork创建子进程之后,子进程执行的是和父进程相同的代码,但可能是不同的代码分支,子进程往往也可以调用一种exec函数族的 一种来执行另一个程序。当进程 调用exec函数族中的一种时,该进程的用户空间代码和数据完全被新的程序替换掉。从新的程序的启动历程开始执行,调用exec并不是创建新进程【调用前 和 调用后进程ID都是一样的,内容换了壳没有换,只是去执行另一个程序去了】。
二.exec函数族的成员
1.int execl(const char * path,const char * arg,....);
2.int execlp(const char * file,const char * arg,……);
3.int execv (const char * path, char * const argv[ ]);
4.int execve(const char * filename,char * const argv[ ],char * const envp[ ]);
5.int execvp(const char *file ,char * const argv []);
#include<unistd.h> int execl(const char * path,const char * arg,....);
execl
()用来执行参数
path
字符串所代表的文件路径,接下来的参 数代表执行该文件时传递过去的 argv
〔
0
〕、
argv[1]
……,最后一个 参数必须用空指针(NULL
)作结束。 如果执行成功则函数不会返回,执行失败则直接返回-1
,失败原因 存于 errno
中。
代码Demo
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
using namespace std;
int
main(int argc, char*argv[])
{
const char* filename = "tmp_file";
int fd;
if ((fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0777)) == -1){
perror("file exist");
exit(1);
}
dup2(fd, STDOUT_FILENO);
close(fd);
execl("/bin/ls", "ls", "-l", "-a", NULL); // no success return value
perror("execl error");
return 0;
}
#include<unistd.h> int execlp(const char * file,const char * arg,……
)
;
execlp()会从
PATH
环境变量所指的目录中查找符合参数
file
的文 件名,找到后便执行该文件,然后将第二个以后的参数当做该文件 的 argv[0]
、
argv[1]
……,最后一个参数必须用空指针(
NULL
)作 结束。 如果执行成功则函数不会返回,执行失败则直返回-1
,失败原因 存于 errno
中。
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int
main(int argc, char*argv[])
{
pid_t pid;
printf("----start---\n");
pid = fork();
if(pid == 0){
execlp("ls", "ls", "-la", "./", NULL);
}else if(pid > 0){
sleep(2);
cout << "hello world" << endl;
}else{
perror("fork error");
exit(1);
}
return 0;
}
其它三个函数 我就不说了 用的不多 ,我 介绍经常用的 就可以了。我介绍一下这几个函数的一般规律把
这几个函数其实还有 联系的