您的位置:首页 > 其它

exec系列函数(execl,execlp,execle,execv,execvp)使用

2015-05-06 20:01 591 查看
本节目标:

exec替换进程映像
exec关联函数组(execl、execlp、execle、execv、execvp)
一,exec替换进程映像
在进程的创建上Unix采用了一个独特的方法,它将进程创建与加载一个新进程映象分离。这样的好处是有更多的余地对两种操作进行管理。

当我们创建了一个进程之后,通常将子进程替换成新的进程映象,这可以用exec系列的函数来进行。当然,exec系列的函数也可以将当前进程替换掉。

例如:在shell命令行执行ps命令,实际上是shell进程调用fork复制一个新的子进程,在利用exec系统调用将新产生的子进程完全替换成ps进程。

二,exec系列函数(execl、execlp、execle、execv、execvp)
包含头文件<unistd.h>

功能:

用exec函数可以把当前进程替换为一个新进程,且新进程与原进程有相同的PID。exec名下是由多个关联函数组成的一个完整系列,

头文件<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[]);

参数:

path参数表示你要启动程序的名称包括路径名

arg参数表示启动程序所带的参数,一般第一个参数为要执行命令名,不是带路径且arg必须以NULL结束

返回值:成功返回0,失败返回-1

注:上述exec系列函数底层都是通过execve系统调用实现:

#include <unistd.h>

int execve(const char *filename, char *const argv[],char *const envp[]);

DESCRIPTION:
execve() executes the program pointed to by filename.  filename must be
either a binary executable, or a script starting with  a  line  of  the form

以上exec系列函数区别:

1,带l 的exec函数:execl,execlp,execle,表示后边的参数以可变参数的形式给出且都以一个空指针结束。

示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
printf("entering main process---\n");
execl("/bin/ls","ls","-l",NULL);
printf("exiting main process ----\n");
return 0;
}

[code]我感觉execl的第一个参数和第二个参数有重叠,帮我 ...
如题,我学习了一下execl函数的用法:
#include<unistd.h>
int main()
{
execl("ls", "ls", "-al");
return 0;
}
OK,什么也不打印,于是我改了一下:
#include<unistd.h>
int main()
{
execl("/bin/ls", "ls", "-al", 0);
return 0;
}
很奇怪啊,execl第一个参数必须是path,我如果把调用语句改成execl("/bin", "ls", "-al", 0);
发现也不行。那岂不是说这个path参数必须包含可执行程序的名字本身? 可是这样的话,execl的第二个参数就是文件名啊,第二个参数岂不是多余了?

非常疑惑,求解释!
path里面包含了file的名字,那还要第二个file参数干什么呢? 感觉多余?
第2个参数将传给进程,也就是argv[0],进程可以通过查看面子有多大,就能看人下菜碟-哦是随机应变了!。
果然是高手!我验证了你的说法,第二个参数是argv[0],可以是任何东西,不必是可执行文件名。如下图所示:
View Code

三,fcntl()函数中的FD_CLOEXEC标识在exec系列函数中的作用


#include <unistd.h>
#include <fcntl.h>

int fcntl(int fd, int cmd, ... /* arg */ );

File descriptor flags
The following commands manipulate the flags associated with a file
descriptor. Currently, only one such flag is defined: FD_CLOEXEC, the
close-on-exec flag. If the FD_CLOEXEC bit is 0, the file descriptor
will remain open across an execve(2), otherwise it will be closed.

//如果FD_CLOEXEC标识位为0,则通过execve调用后fd依然是打开的,否则为关闭的

F_GETFD (void)
Read the file descriptor flags; arg is ignored.

F_SETFD (long)
Set the file descriptor flags to the value specified by arg.

如:fcntl(fd, F_SETFD, FD_CLOEXEC);

1关闭(标准输出关闭)ls -l无法将结果显示在标准输出
http://www.cnblogs.com/mickole/p/3187409.html

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: