2012-01-13 76 views
13

我正在編寫一個必須處理信號的shell程序。我的相關信號處理相關的代碼如下:在Linux中使用signal.h編譯錯誤

#include <signal.h> 
... 
#include <sys/types.h> 
... 
void installSigactions(int, struct sigaction*); 

void handler_function(int signal_id); 
... 
/*define signal table*/ 
struct sigaction signal_action; 

/*insert handler function*/ 
signal_action.sa_handler = handler_function; 

/*init the flags field*/ 
signal_action.sa_flags = 0; 

/*are no masked interrupts*/ 
sigemptyset(&signal_action.sa_mask); 

/*install the signal_actions*/ 
sigaction(SIGINT, &signal_action, NULL); 

編譯給了我下面的警告和錯誤:

gcc -Wall -ggdb -ansi -static -pedantic -o os1shell2 os1shell2.c 
os1shell2.c:35: warning: 'struct sigaction' declared inside parameter list 
os1shell2.c:35: warning: its scope is only this definition or declaration, 
which is probably not what you want 
os1shell2.c: In function 'main': 
os1shell2.c:66: error: storage size of 'signal_action' isn't known 
os1shell2.c:75: warning: implicit declaration of function 'sigemptyset' 
os1shell2.c:78: warning: implicit declaration of function 'sigaction' 

誰能告訴我爲什麼我得到這些警告和錯誤?

回答

12

它會工作,如果你從你的編譯線刪除-ansi。我懷疑問題是當你指定-ansi時,信號庫的posix部分不包含在內。

如果您確實不想禁用-ansi,則還可以將-D_POSIX_C_SOURCE添加到編譯器選項。

Here is a short discussion of ANSI and the gcc feature test macros

+0

刪除'-ansi'會給我留下: '/tmp/ccl4HmT7.o:In main main':' '/ home/stu1/s11/gaw9451/Courses/OS_3/os1shell2.c:68:undefined' '對handler_function''的引用' 'collect2:ld返回1退出狀態' 添加'-D_POSIX_C_SOURCE'也是一樣的。對此有何想法? – Ataraxia 2012-01-13 05:08:16

+0

你是否在任何地方定義了'handler_function'?它是在你的問題中聲明的,但是沒有代碼。我不得不添加'void handler_function(int signal_id){}',然後你的代碼編譯得很好。 – 2012-01-13 05:11:35

0

請嘗試在「signal.h」之前移動「sys/types.h」

如果不工作,嘗試添加此:

#include <bits/sigaction.h> 

如果仍然不能正常工作,請註明:

1)你的操作系統和版本

2 )你的海灣合作委員會版本

+0

沒有幫助...但這是一個很好的建議 – Ataraxia 2012-01-13 04:49:51

+2

不要直接包含''。甚至在文件的頂部有'#error',這讓你不會這樣做。 – Celada 2012-01-13 05:05:00

+0

'uname -a' 'Linux massachusetts 2.6.32-37-generic#81 -Ubuntu SMP Fri Dec 12 20:35:14 UTC 2011 i686 GNU/Linux' 'gcc --version' 'gcc(Ubuntu 4.4.3'ubuntu5)4.4.3' – Ataraxia 2012-01-13 05:05:43