2.7 进程退出、孤儿进程、僵尸进程
进程退出
status参数为退出的状态,记录进程是什么原因退出的。exit()比_exit()多做了几件事情,调用退出处理函数、刷新I/O缓冲、关闭文件描述符等等,exit()底层也是调用_exit()函数。
/*
#include <stdlib.h>
void exit(int status);
#include <unistd.h>
void _exit(int status);
status参数:是进程退出时的一个状态信息。父进程回收子进程资源的时候可以获取到。
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
printf("hello\n");//\n自动刷新IO缓冲区
printf("world");//写入缓冲区里
// exit(0);//一般使用标准C库的函数,它做的事情更多一些,打印hello world(刷新IO缓冲,将缓冲区数据输出到终端)
_exit(0);//若执行成功,return 0将不会被执行,只打印hello
return 0;
}
孤儿进程
init进程pid为1.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main() {
// 创建子进程
pid_t pid = fork();
// 判断是父进程还是子进程
if(pid > 0) {
printf("i am parent process, pid : %d, ppid : %d\n", getpid(), getppid());
//程序运行时在后台
//父进程退出后,切换到前台
} else if(pid == 0) {
sleep(1);
// 当前是子进程
printf("i am child process, pid : %d, ppid : %d\n", getpid(),getppid());
}
// for循环
for(int i = 0; i < 3; i++) {
printf("i : %d , pid : %d\n", i , getpid());
}
return 0;
}
僵尸进程
释放僵尸进程的另一种方法:杀死父进程,子进程由init进程收养并回收。
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main() {
// 创建子进程
pid_t pid = fork();
// 判断是父进程还是子进程
if(pid > 0) {
while(1) {
printf("i am parent process, pid : %d, ppid : %d\n", getpid(), getppid());
sleep(1);
}
} else if(pid == 0) {
// 当前是子进程
printf("i am child process, pid : %d, ppid : %d\n", getpid(),getppid());
}
// for循环
for(int i = 0; i < 3; i++) {
printf("i : %d , pid : %d\n", i , getpid());
}
return 0;
}