库文件类的包括:
execl execlp execle execv execvp
系统调用的有:
execve
NAME
execl, execlp, execle, execv, execvp, execvpe - execute a file
SYNOPSIS
#include
extern char **environ;
int execl(const char *pathname, const char *arg, ...
/* (char *) NULL */);
int execlp(const char *file, const char *arg, ...
/* (char *) NULL */);
int execle(const char *pathname, const char *arg, ...
/*, (char *) NULL, char *const envp[] */);
int execv(const char *pathname, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
char *const envp[]);
其中:
exec 系列替换过程:pcb 使用以前的只修改,进程实体更换。
以 ps 替换当前程序为例,介绍 exec 系统函数使用,注意该系列方法功能都一样,没有区别,只是参数不同
execl示例:
#include
#include
#include
int main(void)
{
printf("main pid: %d\n", getpid());
//execl 执行成功不返回,直接从新程序的主函数开始执行,只有失败才返回错误码
execl("bin/ps", "ps", "-f", (char*)0);
perror("execl error\n");
exit(0);
}
execve示例
#include
#include
#include
int main(void)
{
//存放传给新程序主函数的参数
char* myargv[] = {"ps", "-f", (char*)0};
//存放传给新程序主函数的环境变量
char* myenvp[] = {"MYSTR = hello", "VAL = 100", (char*)0};
printf("main pid = %d\n", getpid());
execve("bin/ps", myargv, myenvp);
perror("execve error");
exit(0);
}
原程序:
#include
#include
#include
#include
#include
#include
int main(char* argc, char*argv[], char* envp[])
{
printf("main pid = %d\n", getpid());
pid_t pid = fork();
assert(pid != -1);
if (pid == 0)
{
char* myargv[] = {"new", "hello", "abc", "123", (char*)0};
execve("./new", myargv, envp);
perror("execve error");
exit(0);
}
wait(NULL);
printf("main over\n");
exit(0);
}
替换的程序:
#include
#include
#include
#include
#include
int main(int argc, char* argv[], char* envp[])
{
printf("new pid = %d\n", getpid());
int i = 0;
printf("argc = %d\n", argc);
for (; i < argc; ++i)
{
printf("argv[%d] = %s\n", i, argv[i]);
}
for (i = 0; envp[i] != NULL; ++i)
{
printf("envp[i] = %s\n", i, envp[i]);
}
exit(0);
}
运行示例: