Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 13:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save udaya1223/10730660 to your computer and use it in GitHub Desktop.
How to use wait() and waitpid() for handling the child processes using SIGCHLD.
#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
else if ( fork_rv == 0 ){ //Handle child processes
while(counter < numChilds){ //Parent process wait for child processes to complete
printf("Parent waiting for children..\n");
return 0;
/* New process takes a nap and then exits */
void child_code(int delay)
printf("Child %d created.\n", getpid());
/* 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);
/* 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment