[英]Signal handling doesn't work with -ansi or with POSIX define
我正在嘗試使用信號功能(我知道它已被棄用,並且其可移植性存在很多問題,但我不能使用sigaction)。
我還需要使用-ansi和-D_POSIX_C_SOURCE = 200112L進行編譯
如果我使用這些標志之一進行編譯,則信號只能工作一次。 如何在不使用sigaction的情況下使用這些標志獲得相同的行為?
#include <signal.h>
#include <stdio.h>
static void signal_handler(int nbr)
{
(void)nbr;
puts("\nHi ! ");
}
int main(void)
{
signal(SIGINT, signal_handler);
puts("Hi ! ");
while (42);
return (0);
}
請注意,上面的代碼包含一個無限循環。
謝謝 :)
看起來您的系統具有Unix / System V信號機制,該機制將在第一個信號之后將信號操作重置為SIG_DFL。 因此,您必須在信號處理程序本身中重新安裝處理程序:
static void signal_handler(int nbr)
{
signal(SIGINT, signal_handler);
(void)nbr;
puts("\nHi ! ");
}
從信號linux人:
* On glibc 2 and later, if the _BSD_SOURCE feature test macro is not
defined, then signal() provides System V semantics. (The default
implicit definition of _BSD_SOURCE is not provided if one invokes
gcc(1) in one of its standard modes (-std=xxx or -ansi) or defines
various other feature test macros such as _POSIX_SOURCE,
_XOPEN_SOURCE, or _SVID_SOURCE; see feature_test_macros(7).)
我只是隨機嘗試,並使用-D_BSD_SOURCE進行了編譯,在Ubuntu上,它按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.