exec函数族

问题:如果用fork 创建一个进程,但是进程必须是想要执行的另外一个程序?

exec函数族提供了一种在进程中启动另一个程序执行的方法。它可以根据指定的文件名或目录名找到可执行文件,并用它来取代原调用进程的数据段、代码段和堆栈段。在执行完之后,原调用进程的内容除了进程号外,其他全部都被替换了。装载的程序可以使 linux许可的 程序或者脚本。

头文件:#include<unistd.h>

函数原型:

              intexecl(const char *path, const char *arg,…)

              intexeclp(const char *file, const char *arg,…)

              intexecle(const char *path, const char *arg,…, char *const envp[])

              intexecv(const char *path, char *const argv[])

              intexecvp(const char *file, char *const argv[])

              intexecve(const char *path, char *const argv[], char *const envp[])

函数参数:

              path:文件路径,使用该参数需要提供完整的文件路径

              file:文件名,使用该参数无需提供完整的文件路径,终端会自动根据$PATH的值查找文件路径

              arg:以逐个列举方式传递参数

              argv:以指针数组方式传递参数

              envp:环境变量数组

返回值:-1(通常情况下无返回值,当函数调用出错才有返回值-1)

后缀       能力

       l             接收以逗号为分隔的参数列表,列表以NULL作为结束标志

       v            接收一个以NULL结尾的字符串数组的指针

       p            提供文件的完整的路径信息 或 通过$PATH查找文件

       e            使用系统当前环境变量 或 通过envp[]传递新的环境变量

示例代码:

/*************************************************************************

 @Author: wanghao

 @Created Time : Mon 21 May 2018 02:22:01 AMPDT

 @File Name: exec.c

 @Description:

 ************************************************************************/

#include<unistd.h>

#include<sys/types.h>

#include<stdio.h>

int main(void)

{

       pid_tpid;

       char*argv[] = {"ls","-l","/home/wanghao", NULL};

       pid= fork();

       if(pid== 0)

       {

              //execvp("ls",argv);   

              if(execv("/bin/ls",argv)< 0)

              {

                     perror("excelperror!");

                     return-1;

              }

              //execl("/bin/ls","ls","-l","/home/wanghao",NULL);

              //execlp("ls","ls","-l","/home/wanghao",NULL);

       }

       elseif(pid > 0)

       {     

              printf("Parrentporcess,PID = %d\n",getpid());

       }

       return0 ;

}

int execle(const char *path, const char*arg,…, char *const envp[])

int execve(const char *path, char *constargv[], char *const envp[])

上面两个函数很少用到不在举例。

      


猜你喜欢

转载自blog.csdn.net/weixin_42048417/article/details/80396123
今日推荐