char *const ps_argv[] ={"ps", "-o",
"pid,ppid,pgrp,session,tpgid,comm", NULL};
char *const ps_envp[] ={"PATH=/bin:/usr/bin", "TERM=console",
NULL};
execl("/bin/ps", "ps", "-o", "pid,ppid,pgrp,session,tpgid,comm",
NULL);
execv("/bin/ps", ps_argv);
execle("/bin/ps", "ps", "-o", "pid,ppid,pgrp,session,tpgid,comm",
NULL, ps_envp);
execve("/bin/ps", ps_argv, ps_envp);
execlp("ps", "ps", "-o", "pid,ppid,pgrp,session,tpgid,comm",
NULL);
execvp("ps", ps_argv);
execl与execv,execlp与execvp,execle与execve。l(list)与程序中的ps_argv[ ]中元素的一样,把新程序中的每个命令行参数都传给它,参数是可变的,最后一个可变参数是NULL
p(PATH): 不带P的exec函数第一个参数必须是相对路径或绝对路径。
v(vector):与l做比较,用ps_argv
e(environment):一份新的环境变量,程序中的ps_envp
只有execve是真正的系统调用,其他五个函数都调用它。
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
execlp("ps", "ps", "-o",
"pid,ppid,pgrp,session,tpgid,comm", NULL);
perror("exec ps");/*perror( ) 用来将上一个函数发生错误的原因输出到标准设备(stderr)*/
exit(1);
}
exec函数执行成功就不再返回,调用出错才有返回值
perror( ) 用来将上一个函数发生错误的原因输出到标准设备(stderr)。参数 s 所指的字符串会先打印出,后面再加上错误原因字符串