tags:

views:

81

answers:

6

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?

+6  A: 

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.

bstpierre
A: 

They're stand-ins for the nasal demons.

R..
+1, an extra +1 if you have a big nose
Matt Joiner
+6  A: 

The way you've written it, it prints out random garbage. The reason is, you don't pass n to printf. It should be

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

This way, it prints the signal number.

jpalecek
+5  A: 

The signal handler parameter is the signal number, so you can use one function for many signals. See signal(3).

Nikolai N Fetissov
+2  A: 

The single argument for a signal handler function is the signal number (unsurprisingly). From man signal:

 No    Name         Default Action       Description
 18    SIGTSTP      stop process         stop signal generated from keyboard (CTRL + Z usually)
Michael Foukarakis
A: 

It returns the signal number. Check this link for more information on job control signals like the one you have used.

The SIGTSTP signal is an interactive stop signal. Unlike SIGSTOP, this signal 
can be handled and ignored.
Your program should handle this signal if you have a special need 
to leave files or system tables in a secure state when a process is 
stopped. For example, programs that turn off echoing should handle 
SIGTSTP so they can turn echoing back on before stopping.
Praveen S