Skip to content

Instantly share code, notes, and snippets.

@udaya1223
Last active August 29, 2015 13:59
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 udaya1223/10730660 to your computer and use it in GitHub Desktop.
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<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