从信号处理程序打印使用INT写或异步安全功能 [英] Print int from signal handler using write or async-safe functions
问题描述
我想打印一个数字日志或使用写
(或任何异步安全功能)的信号处理器中的一个终端。我想preFER不使用缓冲I / O。
有一个简单的和推荐的方式做到这一点?
例如在中的printf
,下面我会preFER 写
(或任何ASYN安全功能)。
无效signal_handler(INT SIG)
{
将为pid_t PID;
INT统计;
INT old_errno =错误号; 而((PID = waitpid函数(-1,&放大器;统计,WNOHANG))大于0)
的printf(子%d个终止\\ n,PID); 错误号= old_errno;
返回;
}
打印字符串很容易。在地方的的printf
上面我可以使用(不打印 PID
)
写(STDOUT_FILENO,终止子,16);
如果你真的坚持从信号处理程序做印刷,你基本上有两个选择:
-
块的信号,除非你处理的信号创建一个专用的线程。这种特殊的线程可以简单地执行
为(;;)暂停();
,自暂停
是异步信号安全中,信号处理程序被允许使用它想要的任何功能;它没有仅限于异步信号安全功能。在另一方面,它确实有访问一个线程安全的方式共享资源,因为你现在正在处理的线程。 -
编写您自己的code整数转换成十进制字符串。这是一个使用
%10
和只是一个简单的循环/ 10
剥离最后一个数字,并将其存储到短数组。
不过,我会极力推荐此操作出来的信号处理程序,使用自管欺骗或相似的。
I want to print a number into log or to a terminal using write
(or any async-safe function) inside a signal handler. I would prefer not to use buffered I/O.
Is there an easy and recommended way to do that ?
For example in place of printf
, below I would prefer write
(or any asyn safe function).
void signal_handler(int sig)
{
pid_t pid;
int stat;
int old_errno = errno;
while((pid = waitpid(-1, &stat, WNOHANG)) > 0)
printf("child %d terminated\n", pid);
errno = old_errno;
return;
}
Printing strings is easy. In place of the printf
above I can use (without printing pid
):
write(STDOUT_FILENO, "child terminated", 16);
If you really insist on doing the printing from a signal handler, you basically have 2 options:
Block the signal except in a dedicated thread you create for handling the signal. This special thread can simply perform
for (;;) pause();
and sincepause
is async-signal-safe, the signal handler is allowed to use any functions it wants; it's not restricted to only async-signal-safe functions. On the other hand, it does have to access shared resources in a thread-safe way, since you're now dealing with threads.Write your own code for converting integers to decimal strings. It's just a simple loop of using
%10
and/10
to peel off the last digit and storing them to a short array.
However, I would highly recommend getting this operation out of the signal handler, using the self-pipe trick or similar.
这篇关于从信号处理程序打印使用INT写或异步安全功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!