Suppression Example

I am trying to use this example from http://www.cs.cf.ac.uk/Dave/C/node24.html :

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

void sighup(); /* routines child will call upon sigtrap */
void sigint();
void sigquit();

main() { 
 int pid;

 /* get child process */

 if ((pid = fork()) < 0) {
    perror("fork");
    exit(1);
 }

if (pid == 0) { /* child */
   printf("\nI am the new child!\n\n");
       signal(SIGHUP,sighup); /* set function calls */
       signal(SIGINT,sigint);
       signal(SIGQUIT, sigquit);
       printf("\nChild going to loop...\n\n");
      for(;;); /* loop for ever */
 }
else /* parent */
 {  /* pid hold id of child */
   printf("\nPARENT: sending SIGHUP\n\n");
   kill(pid,SIGHUP);
   sleep(3); /* pause for 3 secs */
   printf("\nPARENT: sending SIGINT\n\n");
   kill(pid,SIGINT);
   sleep(3); /* pause for 3 secs */
   printf("\nPARENT: sending SIGQUIT\n\n");
   kill(pid,SIGQUIT);
   sleep(3);
 }
}

void sighup() {
   signal(SIGHUP,sighup); /* reset signal */
   printf("CHILD: I have received a SIGHUP\n");
}

void sigint() {
    signal(SIGINT,sigint); /* reset signal */
    printf("CHILD: I have received a SIGINT\n");
}

void sigquit() {
  printf("My DADDY has Killed me!!!\n");
  exit(0);
}

But I do not see any output from the child process.

Is this expected behavior? If so; why?

Many thanks!

+5
source share
3 answers

Your code has a basic race condition. You cannot guarantee that the child has completed the call signalbefore the parent sends the signals. You need to either use some kind of synchronization primitive to make the parent wait for the child to install handlers, or you need to install signal handlers before deploying so that the child inherits them.

, :

  • pipe(p), .
  • fork().
  • close(p[1]); ( ) read(p[0], &dummy, 1);
  • , close(p[0]); close(p[1]); .
  • read, , . close(p[0]); .

2: , :

  • sigprocmask, .
  • sigprocmask , .
  • sigprocmask .
+2

getpid() pid().

0

I'm not quite sure what kind of result you are looking for, but the functions that the child process performs when it receives certain signals from the parent printer print messages indicating what happened.

-1
source

All Articles