Is it possible to signal handler to survive after "exec"?

aditya picture aditya · Feb 25, 2010 · Viewed 12.1k times · Source

I wrote a signal handler for a process, and fork() after that, the signal handler will be applied to both parent and child processes. If I replace the child process with "exec", the signal handler is no more.

I know this happens because "exec" call will overwrite the child process address space with it's own. I just want to know if there is a way to make signal handler work even after "exec" call ?

Answer

paxdiablo picture paxdiablo · Feb 25, 2010

No. From the man pages:

execve() does not return on success, and the text, data, bss, and stack of the calling process are overwritten by that of the program loaded. The program invoked inherits the calling process's PID, and any open file descriptors that are not set to close on exec. Signals pending on the calling process are cleared. Any signals set to be caught by the calling process are reset to their default behaviour. The SIGCHLD signal (when set to SIG_IGN) may or may not be reset to SIG_DFL.

In fact, if the signal handler were still active after the code had been replaced with some very different code, you could expect all sorts of mayhem when the signal occurred. The signal handler is, after all, just an address to call when something happens (discounting SIG_IGN and SIG_DFL for now). Who knows what piece of code would be at that address when you replace the entire text segment?