【发布时间】:2015-01-25 11:05:13
【问题描述】:
在处理类的系统调用时,我遇到了以下代码的问题。无论出于何种原因,当信号处理程序中的 print 语句在其末尾有一个换行符时,它会按预期运行,接收和处理信号并显示消息。然而,当换行符 not 存在时,根本不会显示任何输出。
我不知道为什么会出现这种情况,并希望有人能对这个问题有所了解。
此外,当它确实打印一些东西时,信号似乎只被发送了四次?这段代码有各种奇怪的东西。
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
void alarm_handler(int signo) {
printf("pid : %d\n", getpid());
}
int main(int argc, char* argv[]) {
pid_t pid;
signal(SIGALRM, alarm_handler);
pid = fork();
if(pid == 0)
while(1) { }
else
{
int i;
for(i = 0; i < 5; i++)
{
sleep(1);
kill(pid, SIGALRM);
}
kill(pid, SIGKILL);
}
}
GCC 版本信息
gcc -v
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer//usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.0.0
Thread model: posix
【问题讨论】:
-
我不确定是不是这个问题。但是你不应该在信号处理程序中使用
printf(),因为它不是async-signal-safe functions。有关功能列表,请参阅signal man page。您应该尝试将printf()替换为write()。 -
另外,要查看第五个信号中的 printf,请将
sleep(1)行移到kill(pid, SIGALRM)之后。