How to avoid using printf in a signal handler?

后端 未结 7 958
青春惊慌失措
青春惊慌失措 2020-11-21 06:35

Since printf is not reentrant, it\'s not supposed to be safe to use it in a signal handler. But I\'ve seen lots of example codes that uses printf t

7条回答
  •  臣服心动
    2020-11-21 06:47

    The primary problem is that if the signal interrupts malloc() or some similar function, the internal state may be temporarily inconsistent while it is moving blocks of memory between the free and used list, or other similar operations. If the code in the signal handler calls a function that then invokes malloc(), this may completely wreck the memory management.

    The C standard takes a very conservative view of what you can do in a signal handler:

    ISO/IEC 9899:2011 §7.14.1.1 The signal function

    ¶5 If the signal occurs other than as the result of calling the abort or raise function, the behavior is undefined if the signal handler refers to any object with static or thread storage duration that is not a lock-free atomic object other than by assigning a value to an object declared as volatile sig_atomic_t, or 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 with the first argument equal to the signal number corresponding to the signal that caused the invocation of the handler. Furthermore, if such a call to the signal function results in a SIG_ERR return, the value of errno is indeterminate.252)

    252) If any signal is generated by an asynchronous signal handler, the behavior is undefined.

    POSIX is a lot more generous about what you can do in a signal handler.

    Signal Concepts in the POSIX 2008 edition says:

    If the process is multi-threaded, or if the process is single-threaded and a signal handler is executed other than as the result of:

    • The process calling abort(), raise(), kill(), pthread_kill(), or sigqueue() to generate a signal that is not blocked

    • A pending signal being unblocked and being delivered before the call that unblocked it returns

    the behavior is undefined if the signal handler refers to any object other than errno with static storage duration other than by assigning a value to an object declared as volatile sig_atomic_t, or if the signal handler calls any function defined in this standard other than one of the functions listed in the following table.

    The following table defines a set of functions that shall be async-signal-safe. Therefore, applications can invoke them, without restriction, from signal-catching functions:

    _Exit()             fexecve()           posix_trace_event() sigprocmask()
    _exit()             fork()              pselect()           sigqueue()
    …
    fcntl()             pipe()              sigpause()          write()
    fdatasync()         poll()              sigpending()
    

    All functions not in the above table are considered to be unsafe with respect to signals. In the presence of signals, all functions defined by this volume of POSIX.1-2008 shall behave as defined when called from or interrupted by a signal-catching function, with a single exception: when a signal interrupts an unsafe function and the signal-catching function calls an unsafe function, the behavior is undefined.

    Operations which obtain the value of errno and operations which assign a value to errno shall be async-signal-safe.

    When a signal is delivered to a thread, if the action of that signal specifies termination, stop, or continue, the entire process shall be terminated, stopped, or continued, respectively.

    However, the printf() family of functions is notably absent from that list and may not be called safely from a signal handler.

    The POSIX 2016 update extends the list of safe functions to include, in particular, a large number of the functions from , which is a particularly valuable addition (or was a particularly frustrating oversight). The list is now:

    _Exit()              getppid()            sendmsg()            tcgetpgrp()
    _exit()              getsockname()        sendto()             tcsendbreak()
    abort()              getsockopt()         setgid()             tcsetattr()
    accept()             getuid()             setpgid()            tcsetpgrp()
    access()             htonl()              setsid()             time()
    aio_error()          htons()              setsockopt()         timer_getoverrun()
    aio_return()         kill()               setuid()             timer_gettime()
    aio_suspend()        link()               shutdown()           timer_settime()
    alarm()              linkat()             sigaction()          times()
    bind()               listen()             sigaddset()          umask()
    cfgetispeed()        longjmp()            sigdelset()          uname()
    cfgetospeed()        lseek()              sigemptyset()        unlink()
    cfsetispeed()        lstat()              sigfillset()         unlinkat()
    cfsetospeed()        memccpy()            sigismember()        utime()
    chdir()              memchr()             siglongjmp()         utimensat()
    chmod()              memcmp()             signal()             utimes()
    chown()              memcpy()             sigpause()           wait()
    clock_gettime()      memmove()            sigpending()         waitpid()
    close()              memset()             sigprocmask()        wcpcpy()
    connect()            mkdir()              sigqueue()           wcpncpy()
    creat()              mkdirat()            sigset()             wcscat()
    dup()                mkfifo()             sigsuspend()         wcschr()
    dup2()               mkfifoat()           sleep()              wcscmp()
    execl()              mknod()              sockatmark()         wcscpy()
    execle()             mknodat()            socket()             wcscspn()
    execv()              ntohl()              socketpair()         wcslen()
    execve()             ntohs()              stat()               wcsncat()
    faccessat()          open()               stpcpy()             wcsncmp()
    fchdir()             openat()             stpncpy()            wcsncpy()
    fchmod()             pause()              strcat()             wcsnlen()
    fchmodat()           pipe()               strchr()             wcspbrk()
    fchown()             poll()               strcmp()             wcsrchr()
    fchownat()           posix_trace_event()  strcpy()             wcsspn()
    fcntl()              pselect()            strcspn()            wcsstr()
    fdatasync()          pthread_kill()       strlen()             wcstok()
    fexecve()            pthread_self()       strncat()            wmemchr()
    ffs()                pthread_sigmask()    strncmp()            wmemcmp()
    fork()               raise()              strncpy()            wmemcpy()
    fstat()              read()               strnlen()            wmemmove()
    fstatat()            readlink()           strpbrk()            wmemset()
    fsync()              readlinkat()         strrchr()            write()
    ftruncate()          recv()               strspn()
    futimens()           recvfrom()           strstr()
    getegid()            recvmsg()            strtok_r()
    geteuid()            rename()             symlink()
    getgid()             renameat()           symlinkat()
    getgroups()          rmdir()              tcdrain()
    getpeername()        select()             tcflow()
    getpgrp()            sem_post()           tcflush()
    getpid()             send()               tcgetattr()
    

    As a result, you either end up using write() without the formatting support provided by printf() et al, or you end up setting a flag that you test (periodically) in appropriate places in your code. This technique is ably demonstrated in the answer by Grijesh Chauhan.


    Standard C functions and signal safety

    chqrlie asks an interesting question, to which I have no more than a partial answer:

    How come most string functions from or the character class functions from and many more C standard library functions are not in the list above? An implementation would need to be purposely evil to make strlen() unsafe to call from a signal handler.

    For many of the functions in , it is hard to see why they were not declared async-signal safe, and I'd agree the strlen() is a prime example, along with strchr(), strstr(), etc. On the other hand, other functions such as strtok(), strcoll() and strxfrm() are rather complex and are not likely to be async-signal safe. Because strtok() retains state between calls, and the signal handler could not easily tell whether some part of the code that is using strtok() would be messed up. The strcoll() and strxfrm() functions work with locale-sensitive data, and loading the locale involves all sorts of state setting.

    The functions (macros) from are all locale-sensitive, and therefore could run into the same issues as strcoll() and strxfrm().

    I find it hard to see why the mathematical functions from are not async-signal safe, unless it is because they could be affected by a SIGFPE (floating point exception), though about the only time I see one of those these days is for integer division by zero. Similar uncertainty arises from , and .

    Some of the functions in could be exempted — abs() for example. Others are specifically problematic: malloc() and family are prime examples.

    A similar assessment could be made for the other headers in Standard C (2011) used in a POSIX environment. (Standard C is so restrictive there's no interest in analyzing them in a pure Standard C environment.) Those marked 'locale-dependent' are unsafe because manipulating locales might require memory allocation, etc.

    • Probably not safe
    • Possibly safe
    • — Not safe
    • — Safe
    • Probably not safe
    • — No functions
    • — Locale-sensitive functions (unsafe)
    • — No functions
    • — No functions
    • — Locale-sensitive functions (unsafe)
    • Possibly safe
    • — Not safe
    • — Allowed
    • — No functions
    • — No functions
    • Possibly safe, probably not safe
    • — No functions
    • — No functions
    • — No functions
    • — Not safe
    • — Not all safe (some are allowed; others are not)
    • — No functions
    • — Not all safe
    • Possibly safe
    • Probably not safe
    • — Locale-dependent (but time() is explicitly allowed)
    • — Locale-dependent
    • — Locale-dependent
    • — Locale-dependent

    Analyzing the POSIX headers would be … harder in that there are a lot of them, and some functions might be safe but many won't be … but also simpler because POSIX says which functions are async-signal safe (not many of them). Note that a header like has three safe functions and many unsafe functions.

    NB: Almost all of the assessment of C functions and headers in a POSIX environment is semi-educated guesswork. It is no sense a definitive statement from a standards body.

提交回复
热议问题