信号处理程序中的格式化I/O [英] Formatted I/O inside signal handler

查看:241
本文介绍了信号处理程序中的格式化I/O的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个SIGSEGV处理程序,该处理程序将消息写入文件(FILE *).我听说fprintf不是可重入的,不应在信号处理程序中调用.是否有它的可重入版本,或提供可在信号处理程序中调用的格式化文件I/O的任何其他函数?

I'd like to write a SIGSEGV handler that writes messages to a file (FILE *). I've heard that fprintf is not reentrant and should not be called inside a signal handler. Is there a reentrant version of it, or any other function that provides formatted file I/O that can be called inside a signal handler?

推荐答案

否.根据C11标准的版本N1570的§ 7.14.1.1¶ 5:

No. According to §7.14.1.1 ¶5 of version N1570 of the C11 standard:

如果[the]信号发生[…],则如果[…]信号处理程序调用标准库中除abort函数,_Exit函数和函数或signal函数[…].

If [the] signal occurs […], the behavior is undefined if […] the signal handler calls any function in the standard library other than the abort function, the _Exit function, the quick_exit function, or the signal function […].

因此,简而言之,您可以调用的唯一标准库函数是:

So in short, the only standard library functions you can call are:

  • abort
  • _Exit
  • quick_exit
  • signal(有附加限制)
  • abort
  • _Exit
  • quick_exit
  • signal (additional restrictions apply)

很显然,这些都不是格式化的I/O函数,因此,如果您要坚持使用标准C,则无能为力.

Obviously, none of those are formatted I/O functions, so if you want to stick to standard C, there's nothing you can do.

这是标准C的观点.但是,如果您可以依赖POSIX,则可以使用其任何 async-safe 函数.异步安全功能之一是write,如您所料,它会写入文件.它需要一个普通的缓冲区,因此,如果要格式化任何内容,就必须自己格式化,而且也可能无法动态分配内存.您还必须注意访问全局变量和静态变量:C标准规定,仅当类型为volatile sig_atomic_t时才可以访问它们.

That was the view of standard C. If, however, you're okay with being dependent upon POSIX, you can use any of its async-safe functions. One of the async-safe functions is write, which, as you might expect, writes to a file. It takes a plain buffer, so if you want to format anything, you'll have to format it yourself, and you might not be able to dynamically allocate memory, either. You also have to be careful about accessing global and static variables: the C standard says you can only access them if the type is volatile sig_atomic_t.

只要您使用的是POSIX平台,就可以跳过这些障碍,从而在信号处理程序中编写一条消息.它不像fprintf那样容易,但是如果必须这样做,它就是这样做的.

Jumping through those hoops will allow you to write a message in the signal handler as long as you're on a POSIX platform. It's not as easy as fprintf, but if you have to do it, that's how it's done.

这篇关于信号处理程序中的格式化I/O的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆