用fork函数创建子进程后,子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程完全由新程序代换。exec只是用另一个新程序替换了当前进程的正文、数据、堆和栈段。
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);
建议最后一个参数使用 (char *)0 代替NULL。
其中只有execve是真正意义上的系统调用,其它都是在此基础上经过包装的库函数。
默认exec 具备 运行 和 传参数 两个功能,不能执行某些shell语句如管道“|”和重定向等。
执行重定向这些Shell可以有两种方式:
1.System函数
#include <stdlib.h>
system("ls -l >> ls.dat");
2.使用exec函数
execlp("sh", "sh", "-c", "ls -l >ls.dat", (char*)0 );
sh
-c:表示从字符串中读取命令,而不是从标准输入中读取。支持占位符。