execl execle execlp
execv execve execvp
简单记忆法:
exec执行新进程
l 用参数列表的方式,最后一个参数时NULL
v 把2参数放在数组内,数组最后一个值是NULL
e 用心的环境变量,最后一个是存放新的环境变量的字符串数组
p 用文件名,非p用的时全路径
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int my_system(char *cmd[])
{
pid_t pid;
int status;
pid_t ret;
char *newenviron[] = { NULL };
pid = fork();
if (pid == -1) {
return -1;
} else if (pid == 0) {
/*child process*/
if (execve(cmd[0], cmd, newenviron) == -1)
_exit(127);
} else {
/*father process*/
while (( ret = waitpid(pid, &status, 0)) == -1) {
if (errno != EINTR)
break;
}
if (ret != -1 && WIFEXITED(status))
return WEXITSTATUS(status);
}
return -1;
}
int main(int argc, char *argv[])
{
int ret;
char *cmd[] = {"/bin/ping", "-c", "5", "127.0.0.1", NULL };
for(ret=0;ret<argc; ret++)
printf("argv[%d] = %s\n", ret, argv[ret]);
ret = my_system(cmd);
printf("system %d\n", ret);
return 0;
}