2010-07-24 74 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.