进程程序替换
fork 创建子进程:
- 想让子进程执行父进程代码的一部分(富二代子承父业)代码共享
- 想让子进程执行和父进程完全不同的事情(富二代创业)
代码也要发生写时拷贝
替换原理
用fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。
替换函数
#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[]);
函数解释
- 这些函数如果调用成功则加载新的程序从启动代码开始执行,不再返回。
- 如果调用出错则返回-1
- 所以exec函数只有出错的返回值而没有成功的返回值(没有返回值的原因是,进程调用到exec函数时,代码将会完全被替换,自然也没有了return)
命名解释
l(list) : 表示参数采用列表
v(vector) : 参数用数组
p(path) : 有p自动搜索环境变量PATH
e(env) : 表示自己维护环境变量
exec举例:替换 ls
#include<stdio.h>
#include<unistd.h>
int main()
{
printf("you should running here...........\n");
execl("/usr/bin/ls","ls", "-i", "-l", "-a", NULL);
printf("you should running here...........\n");
return 0;
}
思考:两个打印函数都会输出吗?
结果如下!只输出了一个打印函数,因为进程调用execl函数后,代码就已经被完全覆盖,包括后面的打印函数。
#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);
}
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
int main()
{
pid_t id = fork();
if(id < 0)
{
perror("fork error!\n");
return 1;
}
if (id == 0)
{
//child 替换的是子进程,因为进程是有独立性的,所以,父进程是不受影响的
sleep(3);
execl("/usr/bin/ls", "ls", "-a", "-l", "-i", NULL);
exit(1);
}
pid_t ret = waitpid(id, NULL, 0);
if(ret > 0)
{
printf("cmd run done ....\n");
}
return 0;
}
综合前面的知识,做一个简易的shell
用下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为sh的方块代表,它随着时间的流逝从左向右移动。shell从用户读入字符串"ls"。shell建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。
然后shell读取新的一行输入,建立一个新的进程,在这个进程中运行程序 并等待这个进程结束。所以要写一个shell,需要循环以下过程:
- 获取命令行
- 解析命令行
- 建立一个子进程(fork)
- 替换子进程(execvp)
- 父进程等待子进程退出(wait)
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#define SIZE 256
#define NUM 16
int main()
{
char cmd[SIZE];
const char *cmd_line ="[temp@VM-0-3-centos 321_lesson]";
while(1){
cmd[0] = 0;
printf("%s", cmd_line);
fgets(cmd, SIZE, stdin);
// printf("%s",cmd);
cmd[strlen(cmd)-1] = '\0';//清空命令行
char* args[NUM];
args[0] = strtok(cmd, " ");//strtok 解析命令行输入的字符串
int i = 1;
do{
args[i] = strtok(NULL," ");
if(args[i] == NULL ){
break;
}
++i;
}while(1);
pid_t id = fork();
if(id < 0){
perror("fork error!\n");
continue;
}
if(id == 0){
//child
execvp(args[0], args);
exit(1);
}
int status = 0;
//parent
pid_t ret = waitpid(id, &status,0 );//ret>0,正常返回子进程ID
if(ret > 0){
printf("status code : %d\n", (status>>8)&0xff);
}
}
return 0;
}