2

I am practicing with signals. When I was compiling the code, I received undeclared SIGALRM and undeclared SIGSTP error messages.

main.c:46:16: error: ‘SIGALARM’ undeclared (first use in this function) signal(SIGALARM, (void (*)(int))sig_alarm);

main.c:68:16: error: ‘SIGSTP’ undeclared (first use in this function) signal(SIGSTP, (void (*)(int))int_handler);

#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>



void sig_alarm(int sig){
    kill(sig,SIGKILL);
}

void parent1(int sig){
    kill(sig, SIGUSR1);
}

void parent2(int sig){
    if(sig == 0){/*child is running*/
        kill(sig, SIGUSR2);
    }else if(sig > 0){/*parent is running*/
        printf("Goodbye!");
        exit(0);
    }
}

void int_handler(int sig){}

void child1(int sig){
    printf("Signal received!");
}

void child2(int sig){
    printf("Child exiting...");
    exit(0);
}

int main(){
    pid_t pid;
    if((pid = fork()) < 0){
        perror("fork error");
    }else if(pid > 0){/*parent*/


        signal(SIGALARM, (void (*)(int))sig_alarm);
        alarm(10);
        signal(SIGTSTP, (void (*)(int))parent1);
        while(1){
            pause();
        }
        alarm(0);


        signal(SIGALARM, (void (*)(int))sig_alarm);

        alarm(10);
        signal(SIGINT, (void (*)(int))parent2);
        while(1){
            pause();
        }
        alarm(0);

    }else{/*child*/


        signal(SIGINT, (void (*)(int))int_handler);
        signal(SIGSTP, (void (*)(int))int_handler);


        signal(SIGUSR1, (void (*)(int))child1);
        while(1){
            pause();
        }



        signal(SIGUSR2, (void (*)(int))child2);
        while(1){
            pause();
        }  
    }
    return 0;
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Echo111
  • 139
  • 2
  • 9
  • See [How to avoid using `printf()` in a signal handler](http://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler/) for details on the limitations of what you can do in a signal handler. Note, too, that your messages should end with a newline. – Jonathan Leffler Oct 06 '16 at 23:23

1 Answers1

4

Read the signal(7) man page to get the valid signal names.

The correct names are SIGTSTP (or SIGSTOP - it's not clear what your exact intention is) and SIGALRM.

Note that SIGSTOP cannot be caught.

kaylum
  • 13,833
  • 2
  • 22
  • 31
  • FYI: On my Ubuntu 16.04 system the "man signal" page does not give signal names, but "man 7 signal" does give them. – TonyB Oct 06 '16 at 22:58
  • @TonyB Yes that's right. The linked man page shows that it is in section 7 as well. I have updated the answer to reflect that better. – kaylum Oct 06 '16 at 23:00
  • `SIGSTP` could also be a misspelling of `SIGTSTP` — which is catchable. – Jonathan Leffler Oct 06 '16 at 23:22