2010-07-24 42 views
5

我有下面的C代码:C:信号功能(参数?)

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

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

我很好奇的N参数是在处理函数是什么。当您按^Z时,通常会打印:8320,-1877932264-1073743664。这些数字是什么?


编辑:行动,我写我的printf错误。我纠正它是:

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

现在n的值总是:18.这是什么18?

回答

8

您尚未将任何数字传递给printf()。应该是:

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

n将是你正赶上正负号,你的情况20.说明,请参见man 2 signal。另请注意,该联机帮助页建议使用sigaction()而不是signal

-1

他们是鼻魔的替身。

+0

+1,如果你有一个大鼻子+1 – 2010-07-24 17:47:11

6

你写它的方式,它打印出随机垃圾。原因是,你不通过nprintf。它应该是

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

这样,它会打印信号编号。

6

信号处理程序参数是信号编号,因此您可以对许多信号使用一个函数。请参阅signal(3)

2

信号处理函数的单个参数是信号编号(不出所料)。从man signal

No Name   Default Action  Description 
18 SIGTSTP  stop process   stop signal generated from keyboard (CTRL + Z usually) 
0

它返回信号编号。检查此link以获取更多关于作业控制信号的信息,例如您使用过的信号。

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.