自 printf
不可重入,在信号处理程序中使用它不应该是安全的。但是我看过很多使用 printf
的示例代码这样。
所以我的问题是:我们什么时候需要避免使用 printf
在信号处理程序中,是否有推荐的替代品?
最佳答案
您可以使用一些标志变量,在信号处理程序中设置该标志,并基于该标志调用 printf()
正常运行期间 main() 或程序的其他部分中的函数。
It is not safe to call all functions, such as
printf
, from within a signal handler. A useful technique is to use a signal handler to set aflag
and then check thatflag
from the main program and print a message if required.
alarm_fired
到 1,因为 SIGALRM 被捕获并在主函数中 alarm_fired
检查 value 以有条件地正确调用 printf。static int alarm_fired = 0;
void ding(int sig) // can be called asynchronously
{
alarm_fired = 1; // set flag
}
int main()
{
pid_t pid;
printf("alarm application starting\n");
pid = fork();
switch(pid) {
case -1:
/* Failure */
perror("fork failed");
exit(1);
case 0:
/* child */
sleep(5);
kill(getppid(), SIGALRM);
exit(0);
}
/* if we get here we are the parent process */
printf("waiting for alarm to go off\n");
(void) signal(SIGALRM, ding);
pause();
if (alarm_fired) // check flag to call printf
printf("Ding!\n");
printf("done\n");
exit(0);
}
volatile sigatomic_t
被认为是更好的做法,这种类型总是以原子方式访问,避免中断访问变量的不确定性。 (阅读:Atomic Data Access and Signal Handling 详细解释)。signal()
建立的信号处理函数或 sigaction()
功能。https://stackoverflow.com/questions/16891019/