函数exec

exec函数族

1. 执行指定目录下的程序

#include <unistd.h>
int execl(const char *path, const char *arg, ...);
                            返回值:若出错,返回-1;若成功,不返回

分析:

  • path: 要执行的程序的绝对路径
  • 变参arg: 要执行的程序的需要的参数
  • 第一arg:占位
  • 后边的arg: 命令的参数
  • 参数写完之后: NULL
  • 一般执行自己写的程序

 

2. execv函数原型:
 

#include <unistd.h>
int execv(const char *path, char *const argv[]);
                            返回值:若出错,返回-1;若成功,不返回

参数:

  • path = /bin/ps
  • char* args[] = {"ps", "aux", NULL};
  • execv("/bin/ps", args);

 

3. 执行PATH环境变量能够搜索到的程序

#include <unistd.h>
int execlp(const char *file, const char *arg, ...);
                            返回值:若出错,返回-1;若成功,不返回

分析:

  • file: 执行的命令的名字
  • 第一arg:占位
  • 后边的arg: 命令的参数
  • 参数写完之后: NULL
  • 执行系统自带的程序
  • execlp执行自定义的程序: file参数绝对路径

 

4. execvp函数原型:

#include <unistd.h>
int execvp(const char *file, char *const argv[]);
                            返回值:若出错,返回-1;若成功,不返回

 

5. 执行指定路径, 指定环境变量下的程序

#include <unistd.h>
int execle(const char *path, const char *arg, ..., char *const envp[]);
                                        返回值:若出错,返回-1;若成功,不返回

分析:

  • path: 执行的程序的绝对路径  /home/itcast/a.out
  • arg: 执行的的程序的参数
  • envp: 用户自己指定的搜索目录, 替代PATH
  • char* env[] = {"/home/itcast", "/bin", NULL};

 

6. execve函数原型:

#include <unistd.h>
int execve(const char *path, char *const argv[], char *const envp[]);
                                        返回值:若出错,返回-1;若成功,不返回

 

二、程序清单:

1. 测试代码:

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

int main()
{
    for(int i = 0; i < 8; ++i){
        printf(" parent i = %d\n", i);
    }
    
    pid_t pid = fork();
    if(pid == 0) {
        execlp("ps", "ps", "aux", NULL);
        perror("execlp");
        exit(1);
    }
    for(int i = 0; i < 3; ++i) {
        printf("----------- i = %d\n", i);
    }
    return 0;
}

输出结果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值