1.函数原型
#include<unistd.h>
int execv(const char *path, char *constargv[]);
2. 用法介绍
execv会停止执行当前的进程,并且以path应用进程替换被停止执行的进程,进程ID没有改变。
path: 代表文件的路径
argv: 传递给应用程序的参数列表, 注意,这个数组的第一个参数应该是应用程序名字本身,并且最后一个参数应该为NULL,不参将多个参数合并为一个参数放入数组。
3. 返回值
如果应用程序正常执行完毕,那么execv是永远不会返回的;当execv在调用进程中返回时,那么这个应用程序应该出错了(可能是程序本身没找到,权限不够...), 此时它的返回值应该是-1,具体的错误代码可以通过全局变量errno查看,还可以通过stderr得到具体的错误描述字符串。
4. 示例
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
int main(void)
{
char *argv[]={"ls","-l","/home",(char *)0};
pid_t pid = fork();
if( pid == 0 ) // this is the child process
{
execv("/bin/ls", argv);
}
return 0;
}
执行结果:
[root@localhost test]# total 68
drwx------ 13 baihaoliang baihaoliang 4096 Jul 21 11:50 baihaoliang
drwxr-xr-x. 20 root root 4096 Oct 22 11:05 gengchaolong
drwxr-xr-x 3 root root 4096 Feb 11 2015 git_test
drwxrwxrwx 7 hudefeng hudefeng 4096 Aug 11 17:42 hudefeng
drwx------. 17 icg icg 4096 Dec 23 2014 icg
drwxr-xr-x. 18 jiangxin jiangxin 4096 Oct 23 14:46 jiangxin
drwxrwxrwx. 2 root root 4096 Aug 3 09:00 lixiao
drwx------. 2 root root 16384 Dec 22 2014 lost+found
drwxrwxrwx. 13 root root 4096 Oct 10 09:19 mobile
drwxr-xr-x. 36 renhongquan renhongquan 4096 Oct 26 14:52 renhongquan
drwxr-xr-x 3 root root 4096 Feb 10 2015 repo_server
drwxrwxrwx 25 tangshun tangshun 4096 Oct 10 14:32 tangshun
drwxrwxrwx 14 root root 4096 Oct 23 11:20 wumingming
drw-rw-rw- 2 root root 4096 Oct 23 13:59 xiexzhishu
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 *constargv[]);
int execvp(const char *file, char *constargv[]);