进程程序替换

✅<1>主页::我的代码爱吃辣

📃<2>知识讲解:Linux------进程替换

☂️<3>开发环境:Centos7

💬<4>前言:我们创建子进程的目的是什么?想让子进程帮我们执行特定的任务。那么如何让子进程去执行一段新的代码呢?

一.背景

二.子进程程序替换

三.替换函数

1.execv

2.execlp

3.execle

4.命名理解

四.实现minishell


一.背景

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

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

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

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

隆重介绍一个接口:

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

测试代码:

cpp 复制代码
#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并未改变。

测试代码:

cpp 复制代码
#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函数:

cpp 复制代码
#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[]);
cpp 复制代码
int execve(const char *path, char *const argv[], char *const envp[]);

函数解释:

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

介绍其中几个:

1.execv

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

测试代码:

cpp 复制代码
#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

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

测试代码:

cpp 复制代码
#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

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

测试代码:

cpp 复制代码
#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

cpp 复制代码
#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调用总结:

cpp 复制代码
#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

代码:

cpp 复制代码
#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;
}
相关推荐
Christal_pyy16 分钟前
树莓派4基于Debian GNU/Linux 12 (Bookworm)添加多个静态ipv4网络
linux·网络·debian
csbDD1 小时前
2025年网络安全(黑客技术)三个月自学手册
linux·网络·python·安全·web安全
小金的学习笔记2 小时前
如何在本地和服务器新建mysql用户和密码
运维·服务器·mysql
EasyNVR2 小时前
EasyRTC智能硬件:实时畅联、沉浸互动、消音护航
运维·服务器·网络·安全·音视频·webrtc·p2p
风口上的猪20153 小时前
thingboard告警信息格式美化
java·服务器·前端
Natsuagin3 小时前
轻松美化双系统启动界面与同步时间设置(Windows + Ubuntu)
linux·windows·ubuntu·grub
我们的五年4 小时前
【Linux网络编程】应用层协议HTTP(请求方法,状态码,重定向,cookie,session)
linux·网络·http
xing.yu.CTF5 小时前
Web入侵实战分析-常见web攻击类应急处置实验2
运维·服务器·windows·web安全·apache·php漏洞·phpstudy后门漏洞
小池先生5 小时前
阿里云子账号管理ECS权限配置全指南
服务器·阿里云·云计算
我们的五年6 小时前
【Linux网络】TCP/IP地址的有机结合(有能力VS100%???),IP地址的介绍
linux·运维·网络·tcp/ip