Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ictlyh
Last active November 30, 2016 10:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ictlyh/9638209f46bc5c223fe9e71ccd2f6f76 to your computer and use it in GitHub Desktop.
Save ictlyh/9638209f46bc5c223fe9e71ccd2f6f76 to your computer and use it in GitHub Desktop.
Demo of handling zombie process.
/*
* Demo of handling zombie process.
* Build: gcc test-handlezombie.c -o test-handlezombie
* Run: ./test-handlezombie
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
static void sig_child(int signo);
int main()
{
pid_t pid;
//创建捕捉子进程退出信号
signal(SIGCHLD,sig_child);
pid = fork();
if (pid < 0)
{
perror("fork error:");
exit(1);
}
else if (pid == 0)
{
printf("I am child process,pid id %d.I am exiting.\n",getpid());
exit(0);
}
printf("I am father process.I will sleep two seconds\n");
//等待子进程先退出
sleep(2);
//输出进程信息
system("ps -o pid,ppid,state,tty,command");
printf("father process is exiting.\n");
return 0;
}
static void sig_child(int signo)
{
pid_t pid;
int stat;
//处理僵尸进程
while ((pid = waitpid(-1, &stat, WNOHANG)) >0)
printf("child %d terminated.\n", pid);
}
@ictlyh
Copy link
Author

ictlyh commented Nov 30, 2016

Program output:

I am father process.I will sleep two seconds
I am child process,pid id 107310.I am exiting.
child 107310 terminated.
PID PPID S TT COMMAND
98698 98697 S pts/0 -bash
107309 98698 S pts/0 ./test-handlezombie.out
107311 107309 R pts/0 ps -o pid,ppid,state,tty,command
father process is exiting.

----------------no zombie process

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment