Print int from signal handler using write or async-safe functions

后端 未结 3 1645
粉色の甜心
粉色の甜心 2020-11-28 13:44

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.

3条回答
  •  独厮守ぢ
    2020-11-28 14:21

    If you insist on using xprintf() inside a signal handler you can always roll your own version that does not rely on buffered I/O:

    #include  /* vsnprintf() */
    
    void myprintf(FILE *fp, char *fmt, ...)
    {
    char buff[512];
    int rc,fd;
    va_list argh;
    va_start (argh, fmt);
    
    rc = vsnprintf(buff, sizeof buff, fmt, argh);
    if (rc < 0  || rc >= sizeof buff) {
            rc = sprintf(buff, "Argh!: %d:\n", rc);
            }
    
    if (!fp) fp = stderr;
    fd = fileno(fp);
    if (fd < 0) return;
    if (rc > 0)  write(fd, buff, rc);
    return;
    }
    

提交回复
热议问题