How to avoid using printf in a signal handler?

后端 未结 7 981
青春惊慌失措
青春惊慌失措 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 07:02

    One technique which is especially useful in programs which have a select loop is to write a single byte down a pipe on receipt of a signal and then handle the signal in the select loop. Something along these lines (error handling and other details omitted for brevity):

    static int sigPipe[2];
    
    static void gotSig ( int num ) { write(sigPipe[1], "!", 1); }
    
    int main ( void ) {
        pipe(sigPipe);
        /* use sigaction to point signal(s) at gotSig() */
    
        FD_SET(sigPipe[0], &readFDs);
    
        for (;;) {
            n = select(nFDs, &readFDs, ...);
            if (FD_ISSET(sigPipe[0], &readFDs)) {
                read(sigPipe[0], ch, 1);
                /* do something about the signal here */
            }
            /* ... the rest of your select loop */
        }
    }
    

    If you care which signal it was, then the byte down the pipe can be the signal number.

提交回复
热议问题