How to use wait() and waitpid() for handling the child processes using SIGCHLD.
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<stdlib.h> | |
#include<signal.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#include <sys/wait.h> | |
#include <string.h> | |
#define DELAY 5 | |
int counter = 0; | |
int main(){ | |
void child_handler(); | |
void child_handler2(); | |
//signal(SIGCHLD, child_handler); | |
signal(SIGCHLD, child_handler2); | |
int numChilds; | |
printf("Enter Number of Childs: "); | |
scanf("%d", &numChilds); | |
printf("\nParent %d creating %d childs..\n\n", getpid(), numChilds); | |
void child_code(); | |
int fork_rv, i; | |
for(i=0; i<numChilds; i++){ | |
fork_rv = fork(); //create new process | |
if ( fork_rv == -1 ) //check for errors | |
perror("fork"); | |
else if ( fork_rv == 0 ){ //Handle child processes | |
child_code(DELAY); | |
} | |
} | |
while(counter < numChilds){ //Parent process wait for child processes to complete | |
printf("Parent waiting for children..\n"); | |
sleep(1); | |
} | |
return 0; | |
} | |
/* New process takes a nap and then exits */ | |
void child_code(int delay) | |
{ | |
printf("Child %d created.\n", getpid()); | |
sleep(delay); | |
exit(17); | |
} | |
/* Wait for children to exit. */ | |
void child_handler(int signum){ | |
int status; | |
pid_t pid; | |
pid = wait(&status); | |
printf("Child %ld exited.\n", (long)pid); | |
counter++; | |
} | |
/* Handle the missing child problem with waitpid() function*/ | |
void child_handler2(int signum){ | |
pid_t p; | |
int status; | |
while((p=waitpid(-1, &status, WNOHANG)) > 0){ | |
printf("Child %ld exited.\n", (long)p); | |
counter++; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment