僵尸进程
如果一个子进程终止了,其父进程没有获取它的终止信息、释放它所占用了的资源,则这样的一个子进程就称为僵尸进程(或者僵死进程)。
一个栗子:
// process.cc
#include <chrono>
#include <thread>
#include <iostream>
#include <unistd.h> // fork()
int main()
{
pid_t p_id = fork();
// 子进程
if (p_id == 0) {
std::cout << "this is child process" << std::endl;
return 0;
}
// 父进程
std::cout << "child process id: " << p_id << std::endl;
// wait(nullptr);
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}
编译运行查看进程状态
g++ process.cc -std=c++11 -o main
./main &
ps -l
在注释了wait(nullptr)时,可以看到第四行为第三行的子进程,其状态为ZN:
取消注释之后:
除了wait函数还有waitpid、waitid、wait3、wait4函数,感兴趣可以自行Google。
孤儿进程
如果一个子进程的父进程在其之前消亡,则其就为一个孤儿进程,将被init进程收养,不会变为僵尸进程。
一个栗子:
#include <chrono>
#include <thread>
#include <iostream>
#include <unistd.h> // fork()
int main()
{
pid_t p_id = fork();
// 子进程
if (p_id == 0) {
std::cout << "this is child process" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10));
return 0;
}
// 父进程
std::cout << "child process id: " << p_id << std::endl;
return 0;
}
g++ process.cc -std=c++11 -o main
./main&
ps -l
可以看到父进程退出之后,子进程休眠10s,子进程的PPID已经变为1,被init进程收养。