我遇到了一个我无法解决的奇怪问题。这是我的代码。
#include <stdio.h>
#include <stropts.h>
#include <signal.h>
#include <sys/types.h>
void handle_signal(int s)
{
char c = getchar();
printf("got char '%c'\n");
if(c == 'q')
{
exit(0);
}
}
int main(int argc, char** argv)
{
sigset(SIGPOLL, handle_signal);
ioctl(0, I_SETSIG, S_RDNORM);
printf("type q to exit");
while(1);
return 0;
}
当我运行该程序时,我在终端中键入了字符,但是没有用!!!我无法收到SIGPOLL信号。有人可以给我一些建议吗?顺便说一句,我的操作系统是ubuntu 12.04。
在Linux上,需要在文件描述符上设置O_ASYNC
标志和F_SETOWN
属性以获取SIGIO
信号(的同义词SIGPOLL
)。信号处理程序只能调用异步信号安全函数:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <ctype.h>
void handle_signal(int) { // Can only use async-signal safe functions here.
char msg[] = "got char c\n";
char* c = msg + (sizeof msg - 3);
if(1 != read(STDIN_FILENO, c, 1) || !isprint(*c))
return;
write(STDOUT_FILENO, msg, sizeof msg - 1);
if(*c == 'q')
exit(EXIT_SUCCESS);
}
int main() {
printf("type q to exit\n");
signal(SIGIO, handle_signal);
fcntl(STDIN_FILENO, F_SETFL, O_ASYNC | fcntl(STDIN_FILENO, F_GETFL));
fcntl(STDIN_FILENO, F_SETOWN, getpid());
sigset_t mask;
sigemptyset(&mask);
for(;;)
sigsuspend(&mask);
return EXIT_SUCCESS;
}
您可能还想看看F_SETSIG
它可以接收您选择的信号并将更多信息接收到信号处理程序中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句