Linux系统编程——exec函数族

当我们需要在子进程中去执行其他的程序的时候,我们就需要用到exec系列函数

#include <unistd.h>
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 *const argv[]);
int execvp(const char *file, char *const argv[]);
int execve(const char *path, char *const argv[], char *const envp[]);

exec函数族有六个但是我们重点需要掌握的主要有以下两个:

int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);

l,p,v,e的含义

参数含义
p系统的的PATH环境
v命令行数组
e使用的环境变量数组
l命令行列表 ,命令行以NULL作为结束标志

exec函数使用的注意事项:
1.调用成功不会返回,调用失败返回-1
2.根据指定文件名找到可执行文件,并用它来调用进程的内容

案例1
execlp函数,使用execlp函数在子进程中显示当前日期

/*
 * 使用execlp函数调用date
 */
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
  pid_t pid =fork(); //利用fork先创建一个子进程
  if(pid<0)
  {
    perror("fork error");
    exit(1);
  }else if(pid==0){ //子进程
     execlp("date","date",NULL); //这里的第一个date代表命令的名称,第二个date代表argv[0]
     perror("execlp error"); //如果execlp调用成功的话,那么一下两行就不会执行了
     exit(1);
  }else if(pid>0){ //父进程
    sleep(1);//让子进程先执行完
    printf("I am the parent process,my id is %d\n",getpid());
  }
  return 0;
}

运行结果:

2020年 12月 04日 星期五 00:46:32 CST
I am the parent process,my id is 1028426

案例2
execl函数,使用execl在子进程中调用我们自己写的函数
1.下面是我自己写的一个小函数,接下来我要在子进程中执行这个函数

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

int main()
{
  printf("I am execl\n");
  return 0;
}

2.execl完整代码

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


int main()
{
  pid_t pid=fork();
  if(pid==-1)
  {
    perror("fork error");
    exit(1);
  }else if(pid==0){ //子进程
    execl("./execl_test","./execl_test",NULL);
    perror("exec error");
    exit(1);
  }else if(pid>0){ //父进程
    sleep(1);
    printf("I am the father,my id id %d\n",getpid());

  }
  return 0;
}

运行结果:

I am execl
I am the father,my id id 1032591
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值