Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. /* program to send signal to child */
  2.  
  3. #include<stdio.h>
  4. #include<signal.h>
  5.  
  6. void sighandler_child(int sig_num){
  7.     printf("\n\nSignal %d caught by the process with pid =  %d\n",sig_num,getpid());   
  8. }
  9.  
  10. int main(){
  11.  
  12.     pid_t pid;
  13.     int termstatus;
  14.     pid = fork();  
  15.  
  16.     if(pid==-1)
  17.         printf("Error whlie creating child process");
  18.  
  19.     //parent sends the signal
  20.     if(pid > 0){
  21.        
  22.         sleep(1); //to let the child establish the handler before parent starts execution
  23.         printf("about to send signal to child\n");
  24.         kill(pid,SIGUSR2);
  25.         printf("sent signal to child\n");
  26.         wait(&termstatus);
  27.         printf("\n\nParent: Child terminated...now I am gonna terminate\n\n");
  28.     }
  29.  
  30.     if(pid==0){
  31.  
  32.         /*   to establish the signal handler..
  33.             the type of the second argument is "sighandler_t" which is actually a pointer to a function...
  34.              void (*sighandler_t)(int)
  35.  
  36.         */
  37.    
  38.         if(signal(SIGUSR2,sighandler_child) == SIG_ERR){
  39.             printf("\n\nError while establishing signal handler\n\n");
  40.             return 2;
  41.         }
  42.    
  43.         sleep(3); //to let the child wait for the parent to send signal
  44.  
  45.         printf("\nChild: I am exiting\n\n");
  46.  
  47.     }
  48.        
  49.        
  50.  
  51.     return 0;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement