linux的exec函数族(转载)

分类: linux系统开发 2009-04-27 15:18 5912人阅读 评论(0) 收藏 举报
参考:http://qzone.qq.com/blog/119994997-1236688022
http://hi.baidu.com/colin719/blog/item/f6ea44e782e1152fb938205c.html

exec函数族包括6个函数:

#include
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, const char *envp[]);
int execv(const char *path, const char *argv[]);
int execve(const char *path, const char *argv[], const char *envp[];
int execvp(const char *file, const char *argv[]);


参数说明:

execl的第一个参数是包括路径的可执行文件,后面是列表参数,列表的第一个为命令path,接 着为参数列表,最后必须以NULL结束。
execlp的第一个参数可以使用相对路径或者绝对路径。
execle,最后包括指向一个自定义环境变量列表的指针,此列表必须以NULL结束。
execv,v表示path后面接收的是一个向量,即指向一个参数列表的指针,注意这个列表的最后 一项必须为NULL。
execve,path后面接收一个参数列表向量,并可以指定一个环境变量列表向量。
execvp,第一个参数可以使用相对路径或者绝对路径,v表示后面接收一个参数列表向量。

exec被调用时会替换调用它的进程的代码段和数据段(但是文件描述符不变),直接返回到调用它的进程的父进程,如果出错,返回-1并设置errno。


  1. #include<sys/types.h> 
  2. #include<unistd.h> 
  3. #include<stdio.h> 
  4. #include<stdlib.h> 
  5. #include<errno.h> 
  6.  
  7. int main() 
  8.  execl("/bin/ls""ls""-al""/etc/passwd"(char *) 0); 


例子:
#include
int main(int argc, char *argv[])
{
char *envp[]={"PATH=/tmp", "USER=lei", "STATUS=testing", NULL};
char *argv_execv[]={"echo", "excuted by execv", NULL};
char *argv_execvp[]={"echo", "executed by execvp", NULL};
char *argv_execve[]={"env", NULL};
if(fork()==0) {
if(execl("/bin/echo", "echo", "executed by execl", NULL)<0)
perror("Err on execl");
}
if(fork()==0) {
if(execlp("echo", "echo", "executed by execlp", NULL)<0)
perror("Err on execlp");
}
if(fork()==0) {
if(execle("/usr/bin/env", "env", NULL, envp)<0)
perror("Err on execle");
}
if(fork()==0) {
if(execv("/bin/echo", argv_execv)<0)
perror("Err on execv");
}
if(fork()==0) {
if(execvp("echo", argv_execvp)<0)
perror("Err on execvp");
}
if(fork()==0) {
if(execve("/usr/bin/env", argv_execve, envp)<0)
perror("Err on execve");
}
}

程序里调用了2 个Linux 常用的系统命令,echo和env。echo会把后面跟的命令行参数原封不动的打印出来,env用来列出所有环境变量。
由于各个子进程执行的顺序无法控制,所以有可能出现一个比较混乱的输出--各子进程打印的结果交杂在一起,而不是严格按照程序中列出的次序。
最常见的错误:
平时的编程中,如果用到了exec 函数族,一定记得要加错误判断语句。因为与其他系统调用比起来,exec很容易受伤,被执行文件的位置,权限等很多因素都能导致该调用的失败。
最常见的错误是:
1)找不到文件或路径,此时errno 被设置为ENOENT;
2)数组argv和envp忘记用NULL结束,此时errno被设置为EFAULT;
3)没有对要执行文件的运行权限,此时errno被设置为EACCES。







system函数:


原型:
#include
int system (const char *string);
功能:
The system function runs the command passed to it as
string and waits for it to complete. The command is
executed as if the command $ sh −c string has been given
to a shell.
【也就是说,system要使用一个shell来启动指定的程序】


例:
#include
#include
int main()
{
printf("Running ps with system/n");
system("ps −ax");
printf("Done./n");
exit(0);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值