进程程序替换

2023-09-17 21:45:50

✅<1>主页::我的代码爱吃辣
📃<2>知识讲解:Linux——进程替换
☂️<3>开发环境:Centos7
💬<4>前言:我们创建子进程的目的是什么?想让子进程帮我们执行特定的任务。那么如何让子进程去执行一段新的代码呢?

一.背景

 二.子进程程序替换

 三.替换函数

1.execv

 2.execlp

 3.execle

4.命名理解

四.实现minishell


 

一.背景

我们创建子进程的目的是什么?想让子进程帮我们执行特定的任务。

1.让子进程执行父进程的一部分代码

2.如果子进程指向一个全新的代码呢?这就是进程的程序替换。

见一见单进程版本进程替换,即父进程指向一个全新的代码:

隆重介绍一个接口:

int execl(const char *path, const char *arg, ...);
  1. path:替换程序的路径。
  2. arg:如何执行该程序。
  3. 可变参数:如何执行该程序的参数等。

 测试代码:

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

int main()
{
    printf("--------------------begin-------------\n");

    execl("/usr/bin/ls", "ls", "-a", "-l", NULL);

    printf("--------------------end---------------\n");

    return 0;
}

注意:

  1. 我们想替换的程序 "ls -a -l"。
  2. ls 的路径:/usr/bin/ls。
  3. "-a" "-l" 时ls命令的参数。
  4. 最后结束要以NULL结尾。

测试结果:

注意:

  1. 进程替换以后我们,并没有看到我们源代码里面的最后一个打印。
  2. 原因是程序在替换以后,在后续执行完ls的代码就会退出了,不会回到execl调用后面。

 二.子进程程序替换

创建好子进程,让子进程调用execl,让子进程去执行替换的程序。

用fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。

测试代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int status;
    printf("--------------------begin-------------\n");
    pid_t pid = fork();

    if (pid == 0)
    {
        // 我们想替换的程序 "ls -a -l"
        // ls 的路径:/usr/bin/ls
        //"-a" "-l" 时ls命令的参数
        // 最后结束要以NULL结尾
        execl("/usr/bin/ls", "ls", "-a", "-l", NULL);
    }
    waitpid(-1, &status, 0);//阻塞等待子进程退出。
    if (WIFEXITED(status))
        printf("子进程退出,退出码:%d\n", WEXITSTATUS(status));
    else
        printf("子进程异常,收到信号%d\n", status & 0x7F);
    printf("--------------------end---------------\n");
    return 0;
}

测试结果:

进程替换原理:

当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动
例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。

 三.替换函数

其实有六种以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[]);

函数解释:

  • 这些函数如果调用成功则加载新的程序从启动代码开始执行,不再返回。
  • 如果调用出错则返回-1。
  • 所以exec函数只有出错的返回值而没有成功的返回值。

 介绍其中几个:

1.execv

int execv(const char *path, char *const argv[]);
  1. path:程序所在的路径,
  2. argv:是一个指针数组,数组每一个元素代表我们需要怎么执行程序。

测试代码:


#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int status;
    printf("--------------------begin-------------\n");
    pid_t pid = fork();

    if (pid == 0)
    {
        // 我们想替换的程序 "ls -a -l"
        // ls 的路径:/usr/bin/ls
        //"-a" "-l" 时ls命令的参数
        // 最后结束要以NULL结尾
        char *argv[] = {"ls", "-a", "-l", NULL};
        execv("/usr/bin/ls", argv);
    }
    waitpid(-1, &status, 0);
    if (WIFEXITED(status))
        printf("子进程退出,退出码:%d\n", WEXITSTATUS(status));
    else
        printf("子进程异常,收到信号%d\n", status & 0x7F);
    printf("--------------------end---------------\n");
    return 0;
}

测试结果:

 2.execlp

int execlp(const char *file, const char *arg, ...);
  1. file:程序名称。
  2. 后续参数:需要怎么执行程序。
  3. 不需要给出程序路径,execlp会自己到环境变量中找对应的程序。

测试代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int status;
    printf("--------------------begin-------------\n");
    pid_t pid = fork();

    if (pid == 0)
    {
        // 我们想替换的程序 "ls -a -l"
        // ls 的路径:/usr/bin/ls
        //"-a" "-l" 时ls命令的参数
        // 最后结束要以NULL结尾
        execlp("ls", "ls", "-a", "-l", NULL);
    }
    waitpid(-1, &status, 0);
    if (WIFEXITED(status))
        printf("子进程退出,退出码:%d\n", WEXITSTATUS(status));
    else
        printf("子进程异常,收到信号%d\n", status & 0x7F);
    printf("--------------------end---------------\n");
    return 0;
}

测试结果:

 3.execle

int execle(const char *path, const char *arg, ...,char *const envp[]);
  1. path:程序路径。
  2. envp:是一个指针数组,用来传输环境变量。
  3. arg:我们如何执行程序。

测试代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    extern char **environ;
    int status;
    printf("--------------------begin-------------\n");
    pid_t pid = fork();

    if (pid == 0)
    {
        // 我们想替换的程序 "ls -a -l"
        // ls 的路径:/usr/bin/ls
        //"-a" "-l" 时ls命令的参数
        // 最后结束要以NULL结尾
        execle("./newdir/otherproc", "otherproc", NULL, environ);
    }
    waitpid(-1, &status, 0);
    if (WIFEXITED(status))
        printf("子进程退出,退出码:%d\n", WEXITSTATUS(status));
    else
        printf("子进程异常,收到信号%d\n", status & 0x7F);
    printf("--------------------end---------------\n");
    return 0;
}

newdir/otherproc.cc

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

using namespace std;

int main()
{

    cout << "hello world"
         << "hello:" << getenv("hello") << endl;
    cout << "hello world"
         << "hello:" << getenv("hello") << endl;
    cout << "hello world"
         << "hello:" << getenv("hello") << endl;

    return 0;
}

测试结果:

4.命名理解

这些函数原型看起来很容易混,但只要掌握了规律就很好记。

  1. l(list) : 表示参数采用列表
  2. v(vector) : 参数用数组
  3. p(path) : 有p自动搜索环境变量PATH
  4. e(env) : 表示自己维护环境变量 

 exec调用总结:

#include <unistd.h>
int main()
{
    char *const argv[] = {"ps", "-ef", NULL};
    char *const envp[] = {"PATH=/bin:/usr/bin", "TERM=console", NULL};
    execl("/bin/ps", "ps", "-ef", NULL);
    // 带p的,可以使用环境变量PATH,无需写全路径
    execlp("ps", "ps", "-ef", NULL);
    // 带e的,需要自己组装环境变量
    execle("ps", "ps", "-ef", NULL, envp);
    execv("/bin/ps", argv);
    // 带p的,可以使用环境变量PATH,无需写全路径
    execvp("ps", argv);
    // 带e的,需要自己组装环境变量
    execve("/bin/ps", argv, envp);
    exit(0);
}

事实上,只有execve是真正的系统调用,其它五个函数最终都调用 execve,所以execve在man手册 第2节,其它函数在man手册第3节。这些函数之间的关系如下图所示。

四.实现minishell

用下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为sh的方块代表,它随着时间的流逝从左向右移动。shell从用户读入字符串"ls"。shell建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。

 然后shell读取新的一行输入,建立一个新的进程,在这个进程中运行程序 并等待这个进程结束。
所以要写一个shell,需要循环以下过程:

1. 获取命令行
2. 解析命令行
3. 建立一个子进程(fork)
4. 替换子进程(execvp

代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <assert.h>

#define SEP " "
#define MAX 1024
#define MAX_SUB 64

// 分割命令"ls -a -l" --> "ls","-a" "-l"
void split(char buff[], char *subbuff[])
{
    assert(buff);
    assert(subbuff);

    int i = 0;
    subbuff[i++] = strtok(buff, SEP);
    while (subbuff[i++] = strtok(NULL, SEP)) // 如果没有找到分割,就会返回NULL
        ;
}

// 代码测定,打印命令
void debug(char *subbuff[])
{
    int i = 0;
    while (subbuff[i])
    {
        printf("%s\n", subbuff[i++]);
    }
}

// 显示环境变量
void showenv()
{
    extern char **environ;
    for (int i = 0; environ[i]; i++)
    {
        printf("[%d]:%s\n", i, environ[i]);
    }
}

int main()
{
    int status = 0;            // 退出码参数
    char myenv[32][512] = {0}; // 用户自定义环境变量
    int index_env = 0;
    int last_exit = 0;
    while (1)
    {
        char buff[MAX] = {0}; // 存储命令行输入的命令字符串
        char *subbuff[MAX_SUB] = {NULL};
        printf("wq@[aliyum]$:");
        fflush(stdout);
        // 1.获得命令字符串
        fgets(buff, sizeof(buff), stdin);

        // 2.解析命令
        // ls -a -l\n\0,strlen=9,index(\n)=8,去除回车。
        buff[strlen(buff) - 1] = '\0';

        // 分割字符串
        split(buff, subbuff);

        // 处理内建命令
        //  注意:cd,export,env,echo,等命令都是内建命令,即这些命令不能创建子进程执行,只能bash自己执行
        if (strcmp(subbuff[0], "cd") == 0)
        {
            if (subbuff[1] != NULL)
                chdir(subbuff[1]);

            continue;
        }
        else if (strcmp(subbuff[0], "export") == 0)
        {
            if (subbuff[1] != NULL)
            {
                // 这里不能将subbuff[1]直接导入环境变量,因为环境变量表存储的都是指针,必须使用一个单独空间
                strcpy(myenv[index_env], subbuff[1]);
                putenv(myenv[index_env++]);
            }
            continue;
        }
        else if (strcmp(subbuff[0], "env") == 0)
        {
            showenv();
            continue;
        }
        else if (strcmp(subbuff[0], "echo") == 0)
        {
            // echo $PATH
            if (subbuff[1][0] == '$')
            {
                if (subbuff[1][1] == '?') // echo $?//最近一次推出吗
                {
                    printf("%d\n", last_exit);
                }
                else // 提取环境变量
                {
                    // PATH
                    char *subenv = subbuff[1] + 1;
                    char *get_env = getenv(subenv);
                    if (get_env != NULL)
                    {
                        printf("%s=%s\n", subenv, get_env);
                    }
                }
            }
            continue;
        }
        if (strcmp(subbuff[0], "ls") == 0)
        {
            int comm_index = 0;
            while (subbuff[comm_index])
            {
                comm_index++;
            }
            // 增加高亮
            subbuff[comm_index] = "--color=auto";
        }

        // 3.创建子进程
        pid_t pid = fork();
        assert(pid >= 0);

        if (pid == 0) // 子进程
        {
            extern char **environ;
            // 4. 程序替换
            execve(subbuff[0], subbuff, environ);
        }

        // // 测试
        // debug(subbuff);

        waitpid(pid, &status, 0);
        if (WIFEXITED(status))
        {
            // 子进程退出设置退出码
            last_exit = WEXITSTATUS(status);
        }
    }

    return 0;
}

更多推荐

Postgresql JIT README翻译

WhatisJust-in-TimeCompilation?=================================Just-in-Timecompilation(JIT)istheprocessofturningsomeformofinterpretedprogramevaluationintoanativ

Linux基础指令(四)

目录前言1.find&which指令1.1find1.2which1.3alias1.4where2、grep指令3、xargs指令结语:前言欢迎各位伙伴来到学习Linux指令的第四天!!!在上一篇文章Linux基本指令(三)当中,我们学会了通过学习echo指令,引入了Linux系统中,输出重定向、追加重定向、输入重定

基于海康Ehome/ISUP接入到LiveNVR实现海康摄像头、录像机视频统一汇聚,做到物联网无插件直播回放和控制

LiveNVR支持海康NVR摄像头通EHOME接入ISUP接入LiveNVR分发视频流或是转GB281811、海康ISUP接入配置2、海康设备接入2.1、海康EHOME接入配置示例2.2、海康ISUP接入配置示例3、通道配置3.1、直播流接入类型海康ISUP3.2、海康ISUP设备ID3.3、启用保存3.4、接入成功4

java---jar详解

一、helpC:\Users\lichf1>jar用法:jar{ctxui}[vfmn0PMe][jar-file][manifest-file][entry-point][-Cdir]files...选项:-c创建新档案-t列出档案目录-x从档案中提取指定的(或所有)文件-u更新现有档案-v在标准输出中生成详细输出-

计算机竞赛 深度学习+opencv+python实现车道线检测 - 自动驾驶

文章目录0前言1课题背景2实现效果3卷积神经网络3.1卷积层3.2池化层3.3激活函数:3.4全连接层3.5使用tensorflow中keras模块实现卷积神经网络4YOLOV56数据集处理7模型训练8最后0前言🔥优质竞赛项目系列,今天要分享的是🚩**基于深度学习的自动驾驶车道线检测算法研究与实现**该项目较为新颖

Layui快速入门之第十五节 表格

目录一:基本用法1.引入layui的css和js2.定义一个table标签3.定义user.json数据接口二:数据渲染API方法配置渲染模板配置渲染静态表格渲染静态表格转换已知数据渲染三:表格参数基础属性异步属性返回数据中的特定字段表头属性自定义分页四:监听工具栏事件获取选中行设置行选中状态2.8+获取当前页接口数据

docker run:--privileged=true选项解析(特权模式:赋予容器几乎与主机相同的权限)

文章目录Docker的--privileged=true选项1.Docker容器的安全性1.1LinuxNamespace和Capabilities1.2限制和权限2.Docker的--privileged=true选项2.1--privileged=true的作用2.2--privileged=true的风险3.结论

大数据之Hive

Hive入门Hive是FaceBook开源,基于Hadoop的一个数据仓库工具,可以将结构化的数据映射为一张表,并提供类SQL查询功能。结构化数据是指没有表名和列名的数据文件,映射为一张表就是给这个数据添加表名和列名,让开发人员后续实现需求时只需使用类似SQL的代码来查询数据。Hive本质是一个Hadoop客户端,将H

第30章_瑞萨MCU零基础入门系列教程之IRDA红外遥控实验

本教程基于韦东山百问网出的DShanMCU-RA6M5开发板进行编写,需要的同学可以在这里获取:https://item.taobao.com/item.htm?id=728461040949配套资料获取:https://renesas-docs.100ask.net瑞萨MCU零基础入门系列教程汇总:https://b

【Hierarchical Coverage Path Planning in Complex 3D Environments】

HierarchicalCoveragePathPlanninginComplex3DEnvironments复杂三维环境下的分层覆盖路径规划视点采样全局TSP算法分两层,一层高级一层低级:高层算法将环境分离多个子空间,如果给定体积中有大量的结构,则空间会进一步细分。全局TSP问题;低层算法采用简单的采样路径规划,解决

Go语言简介:历史背景、发展现状及语言特性

一、简述Go语言背景和发展1.软件开发的新挑战多核硬件架构超大规模分布式计算集群Web模式导致的前所未有的开发规模和更新速度2.Go的三位创始人RobPikeUnix的早期开发者UTF-8创始人KenThompsonUnix的创始人C语言创始人1983年获图灵奖RobertGriesemerGoogleV8JSEngi

热文推荐