一、exec替换进程映像
在进程的创建上Unix采用了一个独特的方法,它将进程创建与加载一个新进程映象分离。这样的好处是有更多的余地对两种操作进行管理。
当我们创建了一个进程之后,通常将子进程替换成新的进程映象,这可以用exec系列的函数来进行。当然,exec系列的函数也可以将当前进程替换掉。
(1)、声明:
#include <unistd.h>
int execve(const char *filename, char *const argv[],char *const envp[]);
#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 execvpe(const char *file, char *const argv[],char *const envp[]);
其中第一个是系统调用,下面的5个函数属于库函数(2)、path参数表示要启动程序的名称(包括路径名)、arg参数表示启动程序所带的参数
(3)、返回值:失败返回-1,成功无返回值
二、exec关联函数组(execl、execlp、execle、execv、execvp)的区别
(1)、execl、execlp、execle(带"l")的参数个数是可变的,参数以一个空指针结束。
(2)、execv、execvp、execvpe(带"v")的第二个参数是一个字符串数组,新程序在启动时会把在argv数组中给定的参数传递到main
(3)、这些函数通常都是用execve实现的,这是一种约定俗成的做法,并不是非这样不可。
即:
1、带"l"的是可变参数,带"v"的是字符串数组 ,最后一项都是NULL指针
2、带"p"的是加载的程序继承shell的环境变量PATH,在PATH中搜索程序,带"e"的是用户显示指定环境变量
示例:打印继承到环境变量:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
extern char** environ;
int main()
{
printf("hello pid=%d\n",getpid());
int i;
for (i = 0;environ[i]!=NULL;++i)
{
printf("%s\n",environ[i]);
}
return 0;
}
测试程序:#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
extern char** environ;
int main(int argc,char* argv[])
{
char ch;
char* const envp[] = {"AA=11","BB=12","CC=/bin/ls",NULL};
while (1)
{
ch = getchar();
char *const args[] = {"ls","-l",NULL};
if (ch == 'l')
execl("./hello","hello",NULL,NULL);
if (ch == 'e')
execle("./hello","hello",NULL,envp);
if (ch == 'p')
execlp("ls","ls","-l",NULL);
if (ch == 'v')
execvp("ls",args);
}
printf("Exiting main...\n");
return 0;
}
输出:sh@ubuntu:~/sys$ ./a.out
e
hello pid=3391
AA=11
BB=12
CC=/bin/ls
sh@ubuntu:~/sys$
三、exec和fcntl
设置文件的CLOEXEC位,表示此文件在exec替换的时候被关闭。
示例:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
extern char** environ;
int main(int argc,char* argv[])
{
printf("Entering main...\n");
int flag = fcntl(1,F_SETFD,FD_CLOEXEC);
if (flag == -1)
ERR_EXIT("set error");
execlp("./hello","hello",NULL);
printf("Exiting main...\n");
return 0;
}
文件描述符1倍关闭,程序hello无任何输出。