一.进程创建
1.fork函数
2.linux中fork函数时非常重要的函数,它从已存在进程中创建一个新进程。新进程为子进程,而原进程为父进程。
如以下代码:
1 #include<stdio.h>
2 #include<unistd.h>
3 #include<sys/types.h>
4 int main()
5 {
6 pid_t ret=fork();
7 while(1)
8 {
9 if(ret==0)
10 {
11 //child
12 printf("i am child pid:%d ppid::%d\n",getpid(),getppid());
13 sleep(1);
14 }
15 else{
16 //father
17 printf("i am father pid:%d ppid::%d\n",getpid(),getppid());
18 sleep(1);
19 }
20
21 }
22 return 0;
23 }
~
获取父子进程的pid,父进程返回子进程pid,子进程返回0
2.进程调用fork
进程调用fork,当控制转移到内核中的fork代码后,内核做
分配新的内存块和内核数据结构给子进程
将父进程部分数据结构内容拷贝至子进程
添加子进程到系统进程列表当中
fork返回,开始调度器调度
所以,fork之前父进程独立执行,fork之后,父子两个执行流分别执行。注意,fork之后,谁先执行完全由调度器决定
3.写时拷贝
通常,父子代码共享,父子再不写入时,数据也是共享的,当任意一方试图写入,便以写时拷贝的方式各自一份副本。
fork常规用法
一个父进程希望复制自己,使父子进程同时执行不同的代码段。例如,父进程等待客户端请求,生成子进程来处理请求。
一个进程要执行一个不同的程序。例如子进程从fork返回后,调用exec函数。
二.进程终止
1.进程退出场景
代码运行完毕,结果正确
代码运行完毕,结果不正确
代码异常终止
2.正常终止
1.从main返回
2.调用exit
3.调用_exit
3.exit函数
#include <unistd.h>
void exit(int status);
exit最后也会调用exit, 但在调用exit之前,还做了其他工作:
1. 执行用户通过 atexit或on_exit定义的清理函数。
2. 关闭所有打开的流,所有的缓存数据均被写入
3. 调用_exit
4._exit函数
直接终止进程,不会清空缓冲区
return退出
return是一种更常见的退出进程方法。执行return n等同于执行exit(n),因为调用main的运行时函数会将main的返回值当做 exit的参数
三.进程等待
1.进程等待必要性
1.子进程退出,父进程如果不管不顾,就可能造成‘僵尸进程’的问题,进而造成内存泄漏。
2.另外,进程一旦变成僵尸状态,那就刀枪不入,“杀人不眨眼”的kill -9 也无能为力,因为谁也没 法杀死一个已经死去的进程。
3.最后,父进程派给子进程的任务完成的如何,我们需要知道。如,子进程运行完成,结果对还是 不对,或者是否正常退出。父进程通过进程等待的方式,回收子进程资源
2.进程等待的方法
wait(int*status)
#include<string.h>
2 #include<sys/wait.h>
3 #include<stdio.h>
4 #include<stdlib.h>
5 #include<unistd.h>
6 #include<sys/types.h>
7 int main()
8 {
9 pid_t ret=fork();
10 if(ret==0)
11 {
12 //child
13 printf("i am child pid:%d ppid::%d\n",getpid(),getppid());
14 sleep(10);
15 exit(0);
16 }
17 else{
18 //father
19 printf("i am father pid:%d ppid::%d\n",getpid(),getppid());
20 int status = 0;
21 pid_t ret = wait(&status);
22 if(ret >= 0){
23 printf("wait child success!, %d\n", ret);
24 printf("status: %d\n", status);
25 printf("child exit code : %d\n", (status>>8)&0xFF);
26 printf("child get signal: %d\n", status&0x7F);
27 }
28 printf("Fahter run ....\n");
29 _exit(1);
30 }
31 return 0;
32 }
~
waitpid()
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:
WIFEXITED(status): 若为正常终止子进程返回的状态,则为真。(查看进程是否是正常退出)
WEXITSTATUS(status): 若WIFEXITED非零,提取子进程退出码。(查看进程的退出码)
options:
WNOHANG: 若pid指定的子进程没有结束,则waitpid()函数返回0,不予以等待。若正常结束,则返回该子进程的ID。
1 #include<string.h>
2 #include<sys/wait.h>
3 #include<stdio.h>
4 #include<stdlib.h>
5 #include<unistd.h>
6 #include<sys/types.h>
7 int main()
8 {
pid_t ids[10];
33 for(int i = 0; i < 10; i++){
34 pid_t id = fork();
35 if(id == 0 ){
36 //child
37 int count = 10;
38 while(count > 0){
39 printf("child do something!: %d, %d\n", getpid(), getppid());
40 sleep(1);
41 count--;
42 }
43 exit(i);
44 }
45 //father
46 ids[i] = id;
47 }
int count=0;
65 while(count<10)
66 {
67 int status=0;
68 pid_t ret=waitpid(ids[count],&status,0);
69 if(ret>0)
70 {
71 printf("wait child sucess %d\n",ret);
72 if(WIFEXITED(status))//子进程正常返回为真,非正常返回为-1,查看进程是否正常退出
73 {
74 printf("child exit code : %d\n",WEXITSTATUS(status));//WEXITSTATUS用来查看退出码,提取子进程退出码
75 }
76 else{
77 printf("this is error output\n");
78 }
79 }
80 count++;
81 }
82 return 0;
83 }
如果子进程已经退出,调用wait/waitpid时,wait/waitpid会立即返回,并且释放资源,获得子进程退出信息。
如果在任意时刻调用wait/waitpid,子进程存在且正常运行,则进程可能阻塞。
如果不存在该子进程,则立即出错返回
获取子进程status
wait和waitpid,都有一个status参数,该参数是一个输出型参数,由操作系统填充。
如果传递NULL,表示不关心子进程的退出状态信息。
否则,操作系统会根据该参数,将子进程的退出信息反馈给父进程。
status不能简单的当作整形来看待,可以当作位图来看待,具体细节如下图(只研究status低16比特位):
只有进程正确运行完了,退出码才有意义,要不退出码毫无意义
3.进程的阻塞等待
阻塞调用是指调用结果返回之前,当前线程会被挂起。调用线程只有在得到结果之后才会返回
在子进程中延时等待5s再走出子进程,其表现出的现象就是阻塞式等待,
如以下代码
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;
}
4.非阻塞式等待
非阻塞调用指在不能立刻得到结果之前,该调用不会阻塞当前线程。(小张在楼下等小王,什么都不干,阻塞式等待,玩手机等,非阻塞式等待)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.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;
}
3.进程的替换
3.1.替换原理
用fork创建子进程后执行的是和父进程相同的程序(但有可能执行不同的代码分支),子进程往往要调用一种exec函数以执行另一个程序。当进程调用一种exec函数时,该进程的用户空间代码和数据完全被新程序替换,从新程序的启动例程开始执行。调用exec并不创建新进程,所以调用exec前后该进程的id并未改变。
3.2.替换函数
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.这些程序一旦调用,子进程的后续代码将不会执行
2.如果调用出错,返回-1;
3.所以exec只有出错的返回值,没有成功的返回值
命名理解:
l(list):表示参数使用列表
p(path):有p系统自己搜索系统变量
v(vector):表示参数使用数组形式
e(envp):表示自己维护系统变量
使用代码如下:
int main()
{
pid_t id = fork();
if(id == 0){
printf("I am a process!\n");
sleep(3);
execl("/usr/bin/ls", "ls", "-a", "-i", "-l",NULL);
//execl("/usr/bin/top", "top",NULL);
//execlp("ls","ls", "-a", "-i", "-l", NULL);
char *myargv[] = {
"ls",
"-a",
"-i",
"-l",
NULL
};
char *myenv[] ={
"MYENV=youcanseemeHAHA",
NULL
};
//execv("/usr/bin/ls",myargv);
//execvp("ls", myargv);
execle("./cmd", "cmd", NULL, myenv);
//execl("./test.sh", "test.sh");
//execl("./test.py", "test.py");
//execl("./mytest", "mytest");
exit(10);
}
int status = 0;
pid_t ret = waitpid(id, &status, 0);
if(ret > 0){
printf("signal: %d\n", status & 0x7F);
printf("exit code: %d\n", (status>>8) & 0xFF);
}
return 0;
}
事实上,只有execve是真正的系统调用,其余函数都在调用execve
总结:
进程创建做了什么:
建立进程控制块pcb(task_struct)(被系统以双链表连接管理),创建页表(mm_struct),映射到物理内存,复制部分数据和代码给子进程,父进程分割时间片给子进程。
进程退出做了什么:
回收pcb,析构页表,刷新缓冲的数据
进程等待在做什么:
父进程等待子进程任务结束,需要知道子进程任务完成的怎么样,需要接受子进程的返回值,并且父进程不可退出(退出造成孤儿进程),分为阻塞等待(waitpid(id,&status,0)和非阻塞等待(waitpid(id,status,WNOHANG))
进程替换做什么:
用子进程调用外部程序,调用成功,子进程后续代码不执行。