linux中进程程序替换

思考:创建子进程的目的?

1.想让子进程执行父进程代码的一部分,执行父进程对应的磁盘代码中的一部分。

2.想让子进程执行一个全新的程序,让子进程想办法,加载磁盘上指定的程序。也就是程序替换。

替换函数:execl(六种函数)

int execl(const char *path, const char *arg,..)

第一个参数为我们的运行指令的地址(例如usr/bin/ls), 第二个参数为选项(ls -a, -b之类的)最后结束NULL;我们可以编写代码来验证一下:

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

int main()
{
    printf("process is running...\n");
    execl("/bin/ls", "ls", NULL);
    perror("execl");  // 如果execl调用失败,则打印错误信息
    printf("process running done...\n");

    return 0;
}

运行结果:

我们也可以 execl("/bin/ls", "ls","-a""-b" NULL),但是为什么第二个printf不打印呢?是因为execl执行完毕后,代码已经全部被覆盖,开始执行新的程序代码,所以printf就无法执行了。 

 int execlp(const char *file,const char *arg,...)

path:如何找到程序的功能,带p字符的函数,不用告诉程序的路径,你只要告诉我是谁,我会自动在环境变量PATH ,进行可执行程序的查找!

execlp("ls","ls","-a","-b",NULL);

int execv(const char*path,char*constargv[ ])

可以将所有的执行参数,放入数组中,统一传递,而不用进行使用可遍参数方案。

execv("/usr/bin/ls",argv[]);

int execvp(const char*path,char*constargv[ ])

同理(execlp),不用带参数路径,直接输入命令就可以调用了。

思考:执行系统命令程序,如果我们想写我们自己的程序怎么办呢?

我们现在创造两个可执行程序,让一个程序去调用另一个可执行程序(用mytest调用mybin)。

创建mybin可执行程序:

1 #include<stdio.h>
  2 int main()
  3 {
  4 
  5 
  6 printf("我是另一个c程序");
  7 printf("我是另一个c程序");
  8 printf("我是另一个c程序");
  9 printf("我是另一个c程序");
 10 printf("我是另一个c程序");
 11 printf("我是另一个c程序");
 12 printf("我是另一个c程序");
 13 
 14 
 15 
 16 }

mytest可执行程序:

1 #include <stdio.h>
  2 #include <unistd.h>
  3 #include<stdlib.h>
  4 #include<assert.h>
  5 #include<sys/types.h>
  6 #include<sys/wait.h>
  7 const char *bin="mybin";
  8 int main()
  9 {
 10     execl("./mybin","mybin",NULL);
 11 }

运行的结果:

我们就调用了mybin程序中的内容。当然我们也可以调用不同语言编写的可执行程序(java python等)。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值