0

I am trying to write a function to install a signal handler on a process to ignore a SIGQUIT signal the first time it is called and then exit on the second SIGQUIT signal. I am intend to use a global variable for the counter to count the number of times SIGQUIT signal is sent.

However I am having issues implementing this. I have found SIG_IGN which would ignore the first SIGQUIT signal, but how would I then detect the first signal to increment the counter (and maybe change the signal() to call the signal handler)?

My code is as below:

// global var counter
int signal_counter = 0;

int main (int argc, const char * argv[]) {

    pid_t child_pid = 0;
    int child_status = 0;

    /* fork a child process... */
    child_pid = fork();

    if(child_pid < 0 ) { /* fork() and check if there were errors */
        perror("fork"); /* print a system-defined error message */
        exit(EXIT_FAILURE);
    }

    else if(child_pid == 0) { /* Child code */
        install_handler();
        for(; ;sleep(1)); /*loop forever*/
    }

    else { /* Parent code */
        printf("Parent processing starts\n");
        printf("\nPARENT: sending first SIGQUIT\n\n");  
        kill(child_pid,SIGQUIT);
        printf("\nPARENT: doing something\n\n");
        sleep(3);
        printf("\nPARENT: sending SIGQUIT again\n\n");  
        kill(child_pid,SIGQUIT);
    }

    return EXIT_SUCCESS;

}

void sigquit() {
    printf("SIGQUIT\n");
    sleep(2);
    exit(0);
}

void install_handler(){
    if (signal_counter == 0){
        signal(SIGQUIT, sigquit);
        signal_counter+=1;  
    }
    else{
        signal(SIGQUIT, sigquit);
    }
}

Any help would be appreciated.

Seb
  • 481
  • 2
  • 6
  • 18

1 Answers1

1

A way to solve it is to use the posix standard. According to it, a signal installed is one shot.

The first time that the signal will arrive, it will start the method specified. Therefore, if another signal arrives, then it will be executed normally (i.e. it will quit your application for a sigquit).

Maxime B.
  • 1,116
  • 8
  • 21