exec函数以及wait函数
(1)exec
实际上,在linux中并没有exec函数,而是有6个以上的exec开头的函数族。
原型:
|
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[]) |
函数名带字母v意味着其参数是以数组的方式提供
函数名带字母p意味着会利用环境变量path来寻找指定的执行文件
函数名带字母e意味着用户提供自定义的环境变量
exec函数是提供了在进程中启动另外一个程序执行的方法,也就是新代码覆盖了之前的代码。
注意:./text a 有三个参数./text , a, NULL
程序:
int main(int argc, char **argv)
{
printf("[%d]\n", __LINE__);
pid_t pid = fork();
if(pid > 0)
{
printf("(parent) PID: %d, PPID: %d\n", getpid(), getppid());
int status;
waitpid(pid, &status, WNOHANG);
printf("child exit code: %d\n", WEXITSTATUS(status));
}
if(pid == 0)
{
//execl("./child_process", "./child_process", "abcd", NULL); //是以列表的形式输出
char *arg[] = {"./child_process", "abcd", NULL};
execv("./child_process", arg); //是以数组的形式输出
//execl("/bin/ls", "ls", "-l", NULL); //不加环境变量,所以ls要输出全路径
//execlp("ls", "ls", "-l", NULL); //调哟了环境变量
printf("xxxx\n"); //如果调用了exec,那么exec调用的函数会覆
//盖了这里整段代码,所以xxxx肯定被覆盖 //了,不能输出了
}
return 0;
}
(2)wait waitpid函数
原型:pid_t wait (int *status)
pid_t waitpid(pid_t pid,int * status,int options)
这里的status 是一个整型指针,是该子进程退出时的状态:status 若为空,则代表不记录子进程结束状态。status 若不为空,则由status记录子进程的结束状态值。
另外,对status状态判断的宏
|
WIFEXITED(status) |
如果子进程正常结束返回的值。取exit或_exit的低8位 |
|
WEXITSTATUS(status) |
取得子进程exit()返回的结束代码,一般会先用WIFEXITED 来判断是否正常结束才能使用此宏 |
|
WIFSIGNALED(status) |
如果子进程是因为信号而结束则此宏值为真 |
|
WTERMSIG(status) |
取得子进程因信号而中止的信号代码,一般会先用WIFSIGNALED 来判断后才使用此宏 |
|
WIFSTOPPED(status) |
如果子进程处于暂停执行情况则此宏值为真。一般只有使用WUNTRACED 时才会有此情况 |
|
WSTOPSIG(status) |
取得引发子进程暂停的信号代码,一般会先用WIFSTOPPED来判断后才使用此宏 |