Last active
August 29, 2015 13:56
-
-
Save matutter/9234649 to your computer and use it in GitHub Desktop.
using wait() to prevent children from zombiefying
This file contains hidden or 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
/* Using 'wait();' and an '__EXIT_STATUS' makes sure we don't have zombies or a race condition */ | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <signal.h> | |
void child(int*); | |
int parent(int); | |
int main(void) | |
{ | |
pid_t pid=1; | |
int n=0; | |
do { | |
if (pid == 0) | |
child(&n); | |
else | |
n = parent(pid); | |
pid = fork(); | |
}while(n!=0); | |
} | |
void child(int* n) { | |
printf("\t\t\t\t Child --> %d\n",getpid()); | |
printf("KID]\tgot %d\n", *n); | |
printf("KID]\tsay %d + 2 = %d\n", *n, *n+2); | |
*n+=2; | |
kill(getpid(),SIGKILL); //child kills itself (becomes a zombie) | |
} | |
int parent(int child_pid) { | |
int n, status; | |
wait(&status); /*removes zombies*/ | |
WEXITSTATUS(status); | |
printf("PARENT] enter a # \t\t 0 to End\n"); | |
scanf("%d",&n); | |
return n; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment