Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: signal function (parameters?)

Tags:

c

signals

I have the following c code:

void handler(int n) {
    printf("n value: %i\n");
}

int main() {
    signal(SIGTSTP, handler);   // ^Z at keyboard
    for(int n = 0; ; n++) {
    }   
}

I am curious what the n parameter is in the handler function. When you press ^Z it usually prints either: 8320, -1877932264 or -1073743664. What are these numbers?


Edit: Ops I wrote my printf wrong. I corrected it to be:

void handler(int n) {
    printf("n value: %i\n",n);
}

Now the value of n is always: 18. What is this 18?

like image 859
sixtyfootersdude Avatar asked Jul 24 '10 16:07

sixtyfootersdude


People also ask

What is signal function C?

Description. The C library function void (*signal(int sig, void (*func)(int)))(int) sets a function to handle signal i.e. a signal handler with signal number sig.

Can a signal handler take arguments?

Signal handlers take one integer argument specifying the signal number, and have return type void . So, you should define handler functions like this: void handler (int signum ) { … }

How many signals does C have?

The C standard defines only 6 signals. They are all defined in signal. h header ( csignal header in C++): SIGABRT – "abort", abnormal termination.

Can a signal handler return a value?

Signal handler is like an interrupt and does not return to anyone.


1 Answers

You haven't passed any number to printf(). Should be:

void handler(int n) {
    printf("n value: %i \n", n);
}

The n will be the signum you are catching, in your case 20. See man 2 signal for a description. Also note that the manpage recommends using sigaction() instead of signal.

like image 103
bstpierre Avatar answered Sep 30 '22 00:09

bstpierre