僵尸进程产生的原因是当前还没有其他进程来回收他的尸体。每个进程死亡后系统都有部分资源被持有没有被释放。保留的资源有PID和退出码以及CPU时间、内存使用量等子进程一生的信息。如果他的父进程也已经死亡,则会由系统的INIT进程接管收尸。因为进程已经死亡,使用Kill是无法杀死他的。可能通过杀死其父进程来结束。每个进程在死亡时都会通过SIGCHILD信号通知父进程。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
void signal_handler(int signo){
printf("this is in the sig handler:%d\n", signo);
}
bool register_signal(int signo){
struct sigaction act;
struct sigaction oldact;
act.sa_handler = signal_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
if(sigaction(signo, &act, &oldact) < 0)
return false;
return true;
}
int main(){
pid_t pid;
pid = fork();
if(pid<0)
{
/* 如果出错 */
printf("error occurred!\n");
}
else if(pid==0)
{
/* 子进程 */
exit(0);
}
else
{
/*进程对SIGCHLD默认动作是忽略,对SIGUSR1,SIGUSR2是终止
* 这里选用kill -SIGUSR1 $parentPID 演示。
* 如果不注册会因为终止进程而无法观察到sleep被中断
* */
register_signal(SIGUSR1);
/* 父进程 */
perror("going to sleep\n");
sleep(300); /* 休眠300秒 */
perror("sleep end\n");
wait(NULL); /* 获取僵尸进程的退出信息 */
}
return 0;
}
运行结果:
[anker@ms lab]$ ./a.out
going to sleep
: Success
this is in the sig handler:10
sleep end
: Interrupted system call
评论 (0)