Last active
August 29, 2015 13:57
-
-
Save hanxi/9426943 to your computer and use it in GitHub Desktop.
子进程的使用,父进程根据signal监听子进程的退出。预防僵尸进程的两种方法。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <sys/wait.h> | |
#include <sys/types.h> | |
#include <unistd.h> | |
int main(void) | |
{ | |
pid_t pid; | |
if ((pid = fork()) < 0) | |
{ | |
fprintf(stderr,"Fork error!/n"); | |
exit(-1); | |
} | |
else if (pid == 0) /* first child */ | |
{ | |
if ((pid = fork()) < 0) | |
{ | |
fprintf(stderr,"Fork error!/n"); | |
exit(-1); | |
} | |
else if (pid > 0) | |
exit(0); /* parent from second fork == first child */ | |
/* | |
* We're the second child; our parent becomes init as soon | |
* as our real parent calls exit() in the statement above. | |
* Here's where we'd continue executing, knowing that when | |
* we're done, init will reap our status. | |
*/ | |
sleep(2); | |
printf("Second child, parent pid = %d/n", getppid()); | |
exit(0); | |
} | |
if (waitpid(pid, NULL, 0) != pid) /* wait for first child */ | |
{ | |
fprintf(stderr,"Waitpid error!/n"); | |
exit(-1); | |
} | |
/* | |
* We're the parent (the original process); we continue executing, | |
* knowing that we're not the parent of the second child. | |
*/ | |
exit(0); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
//循环创建子进程 | |
while(1) | |
{ | |
pid = fork(); | |
if (pid < 0) | |
{ | |
perror("fork error:"); | |
exit(1); | |
} | |
else if (pid == 0) | |
{ | |
printf("I am a child process.\nI am exiting.\n"); | |
//子进程退出,成为僵尸进程 | |
exit(0); | |
} | |
else | |
{ | |
//父进程休眠20s继续创建子进程 | |
usleep(5000); | |
continue; | |
} | |
} | |
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment