目录
进程创建
操作系统会做什么:
- 创建大量内核数据结构对象、变量
- 针对各种结构做初始化
- 加载部分或全部程序对应的代码和数据
- 建立映射关系
- 将进程连入各种数据结构中
fork函数初识
- 概念
fork()函数,它是从已存在进程中创建一个新进程。新进程为子进程,而原进程为父进程。
- 函数原型
#include <unistd.h>
pid_t fork(void);
- 进程调用fork,当控制转移到内核中的fork代码后,内核做:
- 分配新的内存块和内核数据结构给子进程
- 将父进程部分数据结构内容拷贝至子进程
- 添加子进程到系统进程列表当中
- fork返回,开始调度器调度
如图:
当一个进程调用fork之后,就有两个二进制代码相同的进程。而且它们都运行到相同的地方。如下程序:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t pid;
printf("Before: pid id %d\n",getpid());
pid = fork();
if(pid == -1)
{
printf("出错了\n");
exit(-1);
}
printf("After: pid is %d, fork return %d\n",getpid(),pid);
sleep(1);
return 0;
}
我们可以从输出的结果看到,在fork前的printf语句只执行了一次,fork后的printf语句打印了两次,可以看出94764为父进程,94765为子进程,也就是子进程没有打印fork前的printf语句。这是为什么呢???
所以,fork之前父进程独立执行,fork之后,父子两个执行流分别进行。
注意:fork之后,父子共享所有的代码,谁先执行完全由调度器决定。
子进程执行的后续代码 != 共享的所有代码,只不过是子进程只能从这里开始执行。
fork函数返回值
子进程中返回0,父进程中返回子进程的id,出错返回-1.
写时拷贝
- 概念
通常,父子代码共享,父子再不写入时,数据也是共享的,当任意一方试图写入,便以写时拷贝的方式各自一份副本。
- 为什么要写时拷贝,创建子进程的时候就把数据分开不行吗?
- 父进程的数据,子进程不一定全用,即便使用也不一定全部写入,会有浪费空间的嫌疑
- 最理想的情况,只有会被父子修改的数据进行分离拷贝,不需要修改的共享即可(从技术角度实现复杂)
- 如果fork的时候,就无脑拷贝数据给子进程会增加fork的成本
- 所以最终采用写时拷贝:延迟拷贝策略,只有真正使用的时候才给你
fork的常规用法
fork函数不是为了创建子进程而创建子进程,它创建子进程的目的有两种:
- 一个父进程希望复制自己,使父子进程同时执行不同的代码段。例如:父进程等待客户端请求,生成子进程来处理请求。
- 一个进程要执行一个不同的程序。例如:子进程从fork返回后,调用exec函数(做程序替换)
fork调用失败的原因
- 系统进程数达到太多,达到上限(系统会有一个进程数的限定,可以进行修改)
- 实际用户的进程数超过了限制
进程终止
进程退出场景
- 代码运行完毕,结果正确
- 代码运行完毕,结果不正确
- 代码没有运行完,异常终止
退出方法
- 退出码
程序在执行终止后传递值给其父进程,这个值被称为退出码(exit code)或退出状态(exit status)。当程序成功执行时传递 0 ,当程序执行失败时传递 1 或比 1 大的值。
在我们平时写的main函数的代码中,其实return 0的写法是不严谨的,main函数的return的结果就是其退出码。我们总是默认代码是正确的,没有根据执行结果返回相应的退出码。退出码可以自己定义也可以使用系统的错误码表。
- 查看退出码
echo $?
①调用_exit函数
#include <unistd.h>
void _exit(int status);
status定义了父进程的终止状态,父进程通过wait来获取该值。
虽然status是int,但是仅有低8位可以被父进程所用,所以_exit(-1)时,在终端执行$?发现返回值是255。
如图:
②调用exit函数
#include <unistd.h>
void exit(int status);
_exit和exit区别:
- _exit仅仅是直接终止进程,不会有任何刷新操作
- exit在退出进程前,执行用户通过atexit或on_exit定义的清理函数,关闭所有打开的流,所有的缓冲数据均被写入,最后调用_exit.
③main函数return
return是一种更常见的退出进程方法。执行return n等同于执行exit(n),因为调用main的运行时会将main的返回值当作exit的参数。
④异常退出
- 在进程运行过程中,使用kill -9信号使进程异常退出,或者使用ctrl+c迫使进程退出
- 代码异常使进程异常退出
进程等待
为什么要进行进程等待?
需要父进程回收子进程的僵尸进程,父进程要关心子进程的退出码。
进程等待的必要性
- 子进程退出,父进程如果不管不顾,就可能造成僵尸进程的问题,进而造成内存泄漏。
- 进程一旦变成僵尸进程,kill -9也不能将其杀掉
- 我们需要知道父进程派给子进程的任务完成的如何,例如:子进程运行完成,结果是否正确,或者是否正常退出。
- 父进程通过进程等待的方式,回收子进程资源,获取子进程退出信息。
进程等待的方法
①wait方法
#include <sys/tyoes.h>
#include <sys/wait.h>
pid_t wait(int *status);
注意:
用来验证回收僵尸的现象
返回值:成功返回被等待进程pid,失败返回-1
参数:输出型参数,获取子进程退出状态,不关心则可以设置成为NULL。
②waitpid方法
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid,int *status, int options);
注意:
用来获取子进程的退出信息(退出码+退出时的信号编号)
返回值:
- 当正常返回的时候waitpid返回收集到的子进程的进程ID
- 如果设置了选项WNOHANG,而调用waitpid发现没有已退出的子进程可收集,则返回0
- 如果调用中出错,则返回-1,这时errno会被设置成相应的值以指示错误所在
参数pid:
- pid=-1,等待任一个子进程。与wait等效
- pid>0,等待其进程ID与pid相等的子进程
参数status:
- 参数status是一个输出型参数,需要我们传入一个整型变量的地址,以获取子进程退出信息
- WIFEXITED(status):若为正常终止子进程返回的状态,则为真(查看进程是否正常退出)
- WEXITSTATUS(status):若WIFEXITED非零,提取子进程退出码(查看进程退出码)
参数options:
- WNOHANG:若pid指定的子进程没有结束,则waitpid()函数返回0,不予以等待。若正常结束,则返回该子进程的ID
- 小结
- 如果子进程已经退出,调用wait/waitpid时, wait/waitpid会立即返回,并且释放资源,获得子进程退出信息。
- 如果在任意时刻调用wait/waitpid,子进程存在且正常运行,则进程可能阻塞
- 如果不存在该子进程,则立即出错返回。
获取子进程status
- wait和waitpid,都有一个status参数,该参数是一个输出型参数,由操作系统填充。
- 如果传递NULL,表示不关心子进程的退出状态信息。否则操作系统会根据该参数,将子进程的退出信息反馈给父进程
- status不能简单的当作整形来看待,可以当作位图来看待,具体如下图:
代码示例:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
int main()
{
pid_t pid;
if((pid=fork())== -1)
{
perror("fork"),exit(1);
}
if(pid == 0)
{
sleep(20);
exit(10);
}
else
{
int st;
int ret = wait(&st);
if(ret > 0 && (st & 0x7F) == 0)
{
printf("child exit code:%d\n",(st>>8)&0xFF);
}
else if(ret > 0)
{
printf("sig code:%d\n",st&0x7F);
}
}
return 0;
}
等待20秒:
在其他终端将其kill掉:
阻塞、非阻塞代码实现
①阻塞等待方式
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
int main()
{
pid_t pid;
pid = fork();
if(pid < 0)
{
printf("%s fork error\n",__FUNCTION__);
return 1;
}
else if( pid == 0 )
{ //child
printf("child is run, pid is : %d\n",getpid());
sleep(5);
exit(257);
}
else
{
int status = 0;
pid_t ret = waitpid(-1, &status, 0);//阻塞式等待,等待5S
printf("this is test for wait\n");
if( WIFEXITED(status) && ret == pid )
{
printf("wait child 5s success, child return code is :%d.\n",WEXITSTATUS(status));
}
else
{
printf("wait child failed, return.\n");
return 1;
}
}
return 0;
}
②进程的非阻塞等待方式
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
int main()
{
pid_t pid;
pid = fork();
if(pid < 0)
{
printf("%s fork error\n",__FUNCTION__);
return 1;
}
else if( pid == 0 )
{ //child
printf("child is run, pid is : %d\n",getpid());
sleep(5);
exit(1);
}
else
{
int status = 0;
pid_t ret = 0;
do
{
ret = waitpid(-1,&status,WNOHANG);//非阻塞式等待
if(ret == 0)
{
printf("child is running\n");
}
sleep(1);
}while(ret == 0);
if( WIFEXITED(status) && ret == pid )
{
printf("wait child 5s success, child return code is :%d.\n",WEXITSTATUS(status));
}
else
{
printf("wait child failed, return.\n");
return 1;
}
}
return 0;
}
进程程序替换
我们一般在服务器设计(linux编程)的时候,往往需要子进程干两件事情
- 让子进程执行父进程的代码片段
- 让子进程执行磁盘中一个全新的程序
如何进行替换:
- 将磁盘中的程序,加载入内存结构
- 重新建立页表映射,谁执行程序替换就重新建立谁的映射(子进程)
效果:让我们的父进程和子进程彻底分离,并让子进程执行一个全新的程序
替换原理
用fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。
替换函数
①execl函数
int execl(const char *path, const char *arg, ....);
示例:
if(id ==0)
{
//child
//我们想让子进程执行全新的程序,以前是执行父进程的代码片段
printf("我是子进程,我的pid是: %d\n",getpid());
execl("/usr/bin/ls","ls","-a","-l",NULL);
exit(1);
}
//一定是父进程
int status= 0;
int ret = waitpid(id, &status, 0);
if(ret == id)
{
sleep(2);
printf("父进程等待成功!\n");
}
②execlp函数
int execlp(const char *file, const char *arg, ...);
示例:
if(id ==0)
{
//child
//我们想让子进程执行全新的程序,以前是执行父进程的代码片段
printf("我是子进程,我的pid是: %d\n",getpid());
execlp("ls","ls","-a","-l",NULL);
exit(1);
}
//一定是父进程
int status= 0;
int ret = waitpid(id, &status, 0);
if(ret == id)
{
sleep(2);
printf("父进程等待成功!\n");
}
③execle函数
int execle(const char *path, const char *arg, ..., char *const envp[]);
示例:
mycmd.cpp
#include <iostream>
#include <stdlib.h>
int main()
{
// std::cout << "PATH:" << getenv("PATH") <<std::endl;
std::cout << "---------------------------------------"<<std::endl;
std::cout << "MYPATH:" << getenv("MYPATH") << std::endl;
std::cout << "---------------------------------------"<<std::endl;
std::cout << "hello c++" << std::endl;
std::cout << "hello c++" << std::endl;
std::cout << "hello c++" << std::endl;
std::cout << "hello c++" << std::endl;
std::cout << "hello c++" << std::endl;
return 0;
}
myexec.c
if(id ==0)
{
//child
//我们想让子进程执行全新的程序,以前是执行父进程的代码片段
printf("我是子进程,我的pid是: %d\n",getpid());
char *const env_[] = {
(char*)"MYPATH=YouCanSeeMe!",
NULL
};
// execle("./mycmd","mycmd",NULL,environ);
execle("./mycmd","mycmd",NULL, env_);
exit(1);
}
在代码自定义:
用environ设置:
④execv函数
int execv(const char *path, char *const argv[]);
示例:
if(id ==0)
{
//child
//我们想让子进程执行全新的程序,以前是执行父进程的代码片段
printf("我是子进程,我的pid是: %d\n",getpid());
//char *const argv_[] = {
// (char*)"top",
// NULL
// };
char *const argv_[] = {
(char*)"ls",
(char*)"-a",
(char*)"-l",
(char*)"-i",
NULL
};
//execv("/usr/bin/top",argv_);
execv("/usr/bin/ls",argv_);
exit(1);
}
⑤execvp函数
int execvp(const char *file, char *const argv[]);
示例:
if(id ==0)
{
//child
//我们想让子进程执行全新的程序,以前是执行父进程的代码片段
printf("我是子进程,我的pid是: %d\n",getpid());
char *const argv_[]={
(char*)"top",
NULL
};
execvp("top",argv_);
exit(1);
}
//一定是父进程
int status= 0;
int ret = waitpid(id, &status, 0);
if(ret == id)
{
sleep(2);
printf("父进程等待成功!\n");
}
⑥execve函数
int execve(const char *path, char *const argv[], char *const envp[]);
示例:
if(id ==0)
{
//child
//我们想让子进程执行全新的程序,以前是执行父进程的代码片段
printf("我是子进程,我的pid是: %d\n",getpid());
char *const env_[] = {
(char*)"MYPATH=YouCanSeeMe!",
NULL
};
char *const argv_[] = {
(char*)"ls",
(char*)"-a",
(char*)"-l",
(char*)"-i",
NULL
};
execve("/usr/bin/ls",argv_,env_);
exit(1);
}
exec函数族如图所示:
如图可看出,只有execve是真正的系统调用,其他五个函数最终都调用execve。
函数解释
- 这些函数如果调用成功则加载新的程序从启动代码开始执行,不再返回。
- 如果调用出错则返回-1,所以exec函数只有出错的返回值而没有成功的返回值。
简易shell的实现
用下图的时间轴来表示事件的发生次序。其中时间从左向右。shell由标识为sh的方块代表,它随着时间的流逝从左向右移动。shell从用户读入字符串"ls"。shell建立一个新的进程,然后在那个进程中运行ls程序并等待那个进程结束。
所以要自己实现一个简易shell,需要循环以下过程:
- 获取命令行
- 解析命令行
- 建立一个子进程
- 替换子进程
- 父进程等待子进程退出
实现代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>
#define SEP " "
#define NUM 1024
#define SIZE 128
char command_line[NUM];
char *command_args[SIZE];
//extern char** environ;
//对应上层的内建命令
int ChangDir(const char *new_path)
{
chdir(new_path);
return 0;
}
int main()
{
//shell本质上就是一个死循环
while(1)
{
//不关心获取这些属性的接口
//1.显示提示符
printf("[张三@我的主机名 当前目录]# ");
fflush(stdout);
//2获取用户输入
memset(command_line,'\0',sizeof(command_line)*sizeof(char));
fgets(command_line,NUM,stdin);//键盘,标准输入,stdin,获取到的是c风格的字符串,'\0'
command_line[strlen(command_line) - 1] = '\0';//清空\n
//3."ls -s -l -i" -> "ls" "-a" "-l" "-i" 字符串切分
command_args[0] = strtok(command_line,SEP);
//给ls命令添加颜色
int index = 1;
if(strcmp(command_args[0],"ls")== 0) command_args[index++] = (char*)"--color=auto";
//strtok截取成功,返回字符串起始地址
//截取失败,返回NULL
while(command_args[index++] = strtok(NULL,SEP));
//4.TODO,编写内建命令
if(strcmp(command_args[0],"cd") == 0 && command_args[1] != NULL)
{
ChangDir(command_args[1]);
continue;
}
//5.创建进程,执行
pid_t id = fork();
if(id == 0)
{
//child
//6.程序替换
//
execvp(command_args[0],command_args);
exit(1);
}
int status = 0;
pid_t ret = waitpid(id,&status,0);
if(ret > 0)
{
printf("等待子进程成功: sig: %d, code: %d\n",status&0x7F,(status>>8)&0xFF);
}
}
return 0;
}