【Linux】进程程序替换

简介: 【Linux】进程程序替换

思维导图

学习目标

      学习进程替换的原理,掌握一些exec*函数的用法。

一、进程的程序替换的原理

      用fork创建子进程后,子进程执行的是和父进程相同的程序(但有可能执行不同的代码分支),若想让子进程执行另一个程序,往往需要调用一种exec函数。

      当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,并从新程序的启动例程开始执行。这种替换类似于数据修改时的写时拷贝,不会将代码直接覆盖影响到父进程的后续代码。

      进程 = 内核数据结构 + 代码 + 数据,代码和数据是要被替换的,而内核数据结构基本不变,没有释放结构,没有创建新的进程。 我们可以通过代码来检验是否创建了子进程?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
 
int main()
{
  printf("taskexec.....begin\n");
  pid_t id = fork();
 
  if(id == 0)
  {
    printf("child pid : %d\n", getpid());
    sleep(2);
    execvpe("./pragma", argv, environ);
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0)
  {
    if(WIFEXITED(status))
    {
      printf("child quit success, child exit code: %d\n", WEXITSTATUS(status));
    }
    else{
      printf("child quit failed\n");
    }
  }
  printf("taskexec.....end\n");
 
  return 0;
}

      站在被替换的进程的角度来看,本质上就是这个程序被加载到内存中去的。怎么将程序加载到内存中??在Linux系统中,exec*函数类似于加载函数。

      为什么我们要先将程序加载到内存中呢??因为冯诺依曼体系结构要求,程序先放入内存中去,CPU只会去内存去寻找数据和代码。

二、替换函数

这些函数不是系统调用,而是一些封装函数。真正的系统调用函数是execve函数:

2.1 exec*系列函数

      加载过程中需要操作系统进行,这种函数底层包括系统调用,因为要将程序加载到内存中。exec*系列函数执行完毕之后,后续的代码不见是正常的,因为代码被替换了,如果不想让后续代码被替换,我们可以使用多进程,让子进程区完成一些代码覆盖。exec*函数的返回值不用关心,只要替换成功,就不会向后走,反之,如果没有替换成功,就一定往后走。

2.2 利用多进程来进行函数替换

      利用子进程进行函数替换操作,防止父进程的后续代码被覆盖,改成多进程版。创建子进程,让子进程自己去替换,父进程进行等待操作:可以让子进程执行父进程的一份代码,或者让子进程执行一份新的代码。创建子进程是为了让子进程去完成工作,在子进程中程序替换会发生写时拷贝。

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
 
int main()
{
  printf("myprocess begin.....\n");
 
  pid_t id = fork();
  if(id == 0)
  {
    sleep(2);
    execl("/usr/bin/ls", "ls", "-a", "-l", NULL);
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0) 
  {
    printf("father wait success, child exit code: %d\n", WEXITSTATUS(status));
  }
  printf("myprocess end.....\n");
  return 0;
}

2.3 一系列exec*函数(返回值不重要)

2.3.1 execl函数

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

l(list):列表。 列表来记录命令行中执行的命令。

execl函数的参数:第一个参数path:我们执行的程序需要带路径(怎么找到程序,用户要告诉函数), 后面几个参数是可变参数,在命令行中怎么执行,我们就怎么进行传参。

总结:第一个参数的含义是帮我们怎么找到执行的程序,后面几个参数的含义是我们想怎么进行执行程序。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
 
int main()
{
  printf("myprocess begin.....\n");
  execl("/usr/bin/ls", "ls", "-a", "-l", NULL);
  printf("myprocess end.....\n");
  return 0;
}

这种函数不止能替换一些Linux指令,还能替换我们所写的程序:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
 
int main()
{
  printf("myprocess begin.....\n");
  pid_t id = fork();
  if(id == 0)
  {
    sleep(2);
    execl("./test", "test", NULL);
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0) 
  {
    printf("father wait success, child exit code: %d\n", WEXITSTATUS(status));
  }
  printf("myprocess end.....\n");
  return 0;
}
#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <sys/types.h>
 
using namespace std;
 
int main()
{
  cout << "C++: pid: %d\n" << getpid() << endl;
  cout << "C++: pid: %d\n" << getpid() << endl;
  cout << "C++: pid: %d\n" << getpid() << endl;
  return 0;
}

2.3.2 execv函数

int execv(const char* path, const char* argv[]);

v(vector):指针数组,将命令全部存储在数组中,再将数组传递给execv函数。

execv函数的参数:由原来的可变参数变成了指针数组。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
 
int main()
{
  printf("myprocess begin.....\n");
  char* argv[] = {
    "ls",
    "-a",
    "-l",
    NULL
  };
 
  pid_t id = fork();
  if(id == 0)
  {
    sleep(2);
    //execl("/usr/bin/ls", "ls", "-a", "-l", NULL);
    execv("/usr/bin/ls", argv);
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0) 
  {
    printf("father wait success, child exit code: %d\n", WEXITSTATUS(status));
  }
  printf("myprocess end.....\n");
  return 0;
}

2.3.3 execvp函数

      v(vector):指针数组,将命令全部存储在数组中,再将数组传递给execv函数。p(path):路径,用户可以不传要执行的文件的路径(但是文件名要传递),直接告诉exec*,我要执行谁就可以。p:查找这个程序,系统会自动在环境变量PATH中进行查找。

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
 
int main()
{
  printf("myprocess begin.....\n");
  char* argv[] = {
    "ls",
    "-a",
    "-l",
    NULL
  };
 
  pid_t id = fork();
  if(id == 0)
  {
    sleep(2);
    execvp("ls", argv);
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0) 
  {
    printf("father wait success, child exit code: %d\n", WEXITSTATUS(status));
  }
  printf("myprocess end.....\n");
  return 0;
}

2.3.4 execvpe函数

      v(vector):指针数组,将命令全部存储在数组中,再将数组传递给execv函数。p(path):路径,用户可以不传要执行的文件的路径(但是文件名要传递),直接告诉exec*,我要执行谁就可以。p:查找这个程序,系统会自动在环境变量PATH中进行查找。e(environment):环境变量。

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
 
int main()
{
  printf("myprocess begin.....\n");
  char* argv[] = {
    "test",
    NULL
  };
 
  char* engv[] = {
    "haha=1111111",
    "hehe=2222222"
  };
 
  pid_t id = fork();
  if(id == 0)
  {
    sleep(2);
    execvpe("./test", argv, engv);
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0) 
  {
    printf("father wait success, child exit code: %d\n", WEXITSTATUS(status));
  }
  printf("myprocess end.....\n");
  return 0;
}
#include <iostream>
#include <algorithm>
#include <unistd.h>
#include <sys/types.h>
 
using namespace std;
 
int main(int argc, char* argv[], char* engv[])
{
  int i = 0;
  for(i = 0; argv[i]; i++)
  {
    cout << argv[i] << endl;
  }
  for(i = 0; engv[i]; i++)
  {
    cout << engv[i] << endl;
  }
  cout << "C++: pid: %d\n" << getpid() << endl;
  cout << "C++: pid: %d\n" << getpid() << endl;
  cout << "C++: pid: %d\n" << getpid() << endl;
  return 0;
}

      所以,在一个程序中的环境变量和可执行参数是父进程给予的,我们可以通过extern来观察bash进程给予的环境变量和参数部分。

extern char** environ; // 获取父进程的环境变量

   

参数环境变量有三种情况:

  • 用新的环境变量整体替换
  • 用老的环境便令
  • 只增加某一个环境变量:putenv函数
putenv函数:
#include <stdlib.h>
int putenv(char* string);

      putenv函数添加的环境变量会被添加在当前进程的环境变量表中。

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
 
int main()
{
  printf("myprocess begin.....\n");
  char* argv[] = {
    "test",
    NULL
  };
 
  char* engv[] = {
    "haha=1111111",
    "hehe=2222222"
  };
  putenv("papa=333333");
  pid_t id = fork();
  if(id == 0)
  {
    extern char** environ;
    sleep(2);
    execvpe("./test", argv, environ);
    exit(1);
  }
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0) 
  {
    printf("father wait success, child exit code: %d\n", WEXITSTATUS(status));
  }
  printf("myprocess end.....\n");
  return 0;
}

三、函数解释

  • 这些函数如果调用成功则加载新的程序从启动代码开始执行,不在返回
  • 如果调用失败返回-1
  • exec函数只有出错的返回值,而没有成功的返回值
相关文章
|
5月前
|
并行计算 Linux
Linux内核中的线程和进程实现详解
了解进程和线程如何工作,可以帮助我们更好地编写程序,充分利用多核CPU,实现并行计算,提高系统的响应速度和计算效能。记住,适当平衡进程和线程的使用,既要拥有独立空间的'兄弟',也需要在'家庭'中分享和并行的成员。对于这个世界,现在,你应该有一个全新的认识。
224 67
|
4月前
|
Web App开发 Linux 程序员
获取和理解Linux进程以及其PID的基础知识。
总的来说,理解Linux进程及其PID需要我们明白,进程就如同汽车,负责执行任务,而PID则是独特的车牌号,为我们提供了管理的便利。知道这个,我们就可以更好地理解和操作Linux系统,甚至通过对进程的有效管理,让系统运行得更加顺畅。
105 16
|
4月前
|
Unix Linux
对于Linux的进程概念以及进程状态的理解和解析
现在,我们已经了解了Linux进程的基础知识和进程状态的理解了。这就像我们理解了城市中行人的行走和行为模式!希望这个形象的例子能帮助我们更好地理解这个重要的概念,并在实际应用中发挥作用。
89 20
|
3月前
|
监控 Shell Linux
Linux进程控制(详细讲解)
进程等待是系统通过调用特定的接口(如waitwaitpid)来实现的。来进行对子进程状态检测与回收的功能。
70 0
|
3月前
|
存储 负载均衡 算法
Linux2.6内核进程调度队列
本篇文章是Linux进程系列中的最后一篇文章,本来是想放在上一篇文章的结尾的,但是想了想还是单独写一篇文章吧,虽然说这部分内容是比较难的,所有一般来说是简单的提及带过的,但是为了让大家对进程有更深的理解与认识,还是看了一些别人的文章,然后学习了学习,然后对此做了总结,尽可能详细的介绍明白。最后推荐一篇文章Linux的进程优先级 NI 和 PR - 简书。
90 0
|
3月前
|
存储 Linux Shell
Linux进程概念-详细版(二)
在Linux进程概念-详细版(一)中我们解释了什么是进程,以及进程的各种状态,已经对进程有了一定的认识,那么这篇文章将会继续补全上篇文章剩余没有说到的,进程优先级,环境变量,程序地址空间,进程地址空间,以及调度队列。
60 0
|
3月前
|
Linux 调度 C语言
Linux进程概念-详细版(一)
子进程与父进程代码共享,其子进程直接用父进程的代码,其自己本身无代码,所以子进程无法改动代码,平时所说的修改是修改的数据。为什么要创建子进程:为了让其父子进程执行不同的代码块。子进程的数据相对于父进程是会进行写时拷贝(COW)。
62 0
|
6月前
|
Linux 数据库 Perl
【YashanDB 知识库】如何避免 yasdb 进程被 Linux OOM Killer 杀掉
本文来自YashanDB官网,探讨Linux系统中OOM Killer对数据库服务器的影响及解决方法。当内存接近耗尽时,OOM Killer会杀死占用最多内存的进程,这可能导致数据库主进程被误杀。为避免此问题,可采取两种方法:一是在OS层面关闭OOM Killer,通过修改`/etc/sysctl.conf`文件并重启生效;二是豁免数据库进程,由数据库实例用户借助`sudo`权限调整`oom_score_adj`值。这些措施有助于保护数据库进程免受系统内存管理机制的影响。
|
6月前
|
存储 Linux 调度
【Linux】进程概念和进程状态
本文详细介绍了Linux系统中进程的核心概念与管理机制。从进程的定义出发,阐述了其作为操作系统资源管理的基本单位的重要性,并深入解析了task_struct结构体的内容及其在进程管理中的作用。同时,文章讲解了进程的基本操作(如获取PID、查看进程信息等)、父进程与子进程的关系(重点分析fork函数)、以及进程的三种主要状态(运行、阻塞、挂起)。此外,还探讨了Linux特有的进程状态表示和孤儿进程的处理方式。通过学习这些内容,读者可以更好地理解Linux进程的运行原理并优化系统性能。
206 4
|
6月前
|
Linux Shell
Linux 进程前台后台切换与作业控制
进程前台/后台切换及作业控制简介: 在 Shell 中,启动的程序默认为前台进程,会占用终端直到执行完毕。例如,执行 `./shella.sh` 时,终端会被占用。为避免不便,可将命令放到后台运行,如 `./shella.sh &`,此时终端命令行立即返回,可继续输入其他命令。 常用作业控制命令: - `fg %1`:将后台作业切换到前台。 - `Ctrl + Z`:暂停前台作业并放到后台。 - `bg %1`:让暂停的后台作业继续执行。 - `kill %1`:终止后台作业。 优先级调整:
301 5