Linux系统编程(十)exec 族函数

Linux系统编程(十)exec 族函数

  exec 函数族的作用是根据指定的文件名找到可执行文件,并用它来取代调用进程的内容,换句话说,就是在调用进程内部执行一个可执行文件。

  exec 函数族的函数执行成功后不会返回,因为调用进程的实体,包括代码段,数据
段和堆栈等都已经被新的内容取代,只留下进程 ID 等一些表面上的信息仍保持原样,颇有些神似“三十六计”中的“金蝉脱壳”。看上去还是旧的躯壳,却已经注入了新的灵魂。只有调用失败了,它们才会返回 -1,从原程序的调用点接着往下执行。

  以execlexeclp为例。

execl() 函数

  1. 头文件
#include <unistd.h>

extern char **environ;

int execl(const char *path, const char *arg, ...
                /* (char  *) NULL */);
int execlp(const char *file, const char *arg, ...
                /* (char  *) NULL */);
int execle(const char *path, const char *arg, ...
                /*, (char *) NULL, 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[]);

// l(list) 参数地址列表,以空指针结尾
// v(vector) 存有各参数地址的指针数组的地址
// p(path) 按 PATH 环境变量指定的目录搜索可执行文件
// e(environment) 存有环境变量字符串地址的指针数组的地址
  1. 函数原型
int execl(const char *path, const char *arg, ...
                /* (char  *) NULL */);

函数参数:

  • path :指定的可执行程序路径 / 名称
  • arg :执行可执行文件所需要的参数列表。第一个参数没有什么作用,一般使用可执行文件名称代替。从第二个参数开始,为可执行文件所需要的参数列表。参数以 NULL 结束。
  1. 返回值
  • 只有调用失败时,才会有返回值,返回-1,并设置 errorno
  • 调用成功时,无返回值。

示例如下:

#include <unistd.h>
#include <stdio.h>


int main(){
    // 创建一个子进程,在子进程中执行exec函数族中的函数

    pid_t pid = fork();

    if (pid > 0){       // 父进程
        printf("I am parent process: %d\n", getpid());
        sleep(1);
    }
    else if (pid == 0){
        execl("hello", "hello", "NULL");
        printf("I am child process: %d\n", getpid());       // 不会执行
    }

    // 父进程会执行for循环,子进程不会执行for
    for (int i = 0; i < 10; i++){
        printf("i = %d, pid = %d\n", i, getpid());
    }

    return 0;
}

编译执行
execl

execlp() 函数

  1. 包含头文件
#include <unistd.h>
  1. 函数原型
int execlp(const char *file, const char *arg, ...
                       /* (char  *) NULL */);

函数参数:

  • file :需要执行的可执行文件名
  • arg :同 execlarg 参数
  1. 返回值
  • 只有调用失败时,才会有返回值,返回-1,并设置 errorno
  • 调用成功时,无返回值。

在环境变量中,查找指定的可执行文件,找到则执行,找不到则执行不成功。

#include <unistd.h>
#include <stdio.h>


int main(){
    // 创建一个子进程,在子进程中执行exec函数族中的函数

    pid_t pid = fork();

    if (pid > 0){       // 父进程
        printf("I am parent process: %d\n", getpid());
        sleep(1);
    }
    else if (pid == 0){
        execlp("ps", "ps", "aux", NULL);				// 不用指定路径,在环境变量路径中查找
        printf("I am child process: %d\n", getpid());       // 不会执行
    }

    // 父进程会执行for循环,子进程不会执行for
    for (int i = 0; i < 10; i++){
        printf("i = %d, pid = %d\n", i, getpid());
    }

    return 0;
}

编译执行
execlp

一键三连是对我的支持与鼓励!欢迎关注编程小镇,每天涨一点新姿势😄。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值