Async signal safety of fork()

2020-03-20 06:52发布

问题:

According to Oracle's Multithreaded Programming Guide, fork() should be safe-to-use inside signal handlers. But my process got stuck inside signal handler with to following back trace:

 #0  __lll_lock_wait_private () at   ../nptl/sysdeps/unix/sysv/linux/x86_64/lowlevellock.S:95
 #1  0x00007f86e6a9990d in _L_lock_48 () from /lib/x86_64-linux- gnu/libc.so.6
 #2  0x00007f86e6a922ec in ptmalloc_lock_all () at arena.c:242
 #3  0x00007f86e6ad5e82 in __libc_fork () at ./nptl/sysdeps/unix/sysv/linux/x86_64/../fork.c:95
 #4  0x00007f86e7d9f125 in __fork () at ./nptl/sysdeps/unix/sysv/linux/pt-fork.c:25
....
 #7  signal handler called

So as malloc is not safe to be use in signal handler how fork can be?

Thanks in advance.

回答1:

This is now listed as a bug by RedHat:

Bug 1422161 - glibc: fork is not async-signal-safe

...

+++ This bug was initially created as a clone of Bug #1422159 +++

POSIX requires that fork is async-signal-safe. Our current implementation is not.



回答2:

fork() will start a new process by copying some of memory of parents, but both are separate processes. So it is safe to use inside signal handler. Below is example of running child....

#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>

int SHOULD_RUN = 1;
void int_sig_handler(int signal){
        printf("SIG_INT\n");
        if(fork() == 0){
                // child code
                printf("I am Child");
                //signal(SIGINT, int_sig_handler);
                SHOULD_RUN = 1;
                while(SHOULD_RUN){
                        printf("I am Running Still...\n");
                        sleep(1);
                }
                exit(0);
        }else{
                // parent code
                printf("parent");
        }
        SHOULD_RUN = 0;
}


int main(int argc, const char *argv[]){
        signal(SIGINT, int_sig_handler);
        while(SHOULD_RUN){
                sleep(1);
        }
        return 0;
}