Externally disabling signals for a Linux program

前端 未结 5 2058
慢半拍i
慢半拍i 2021-02-13 13:00

On Linux, is it possible to somehow disable signaling for programs externally... that is, without modifying their source code?

Context:

5条回答
  •  攒了一身酷
    2021-02-13 13:56

    The process signal mask is inherited across exec, so you can simply write a small wrapper program that blocks SIGINT and executes the target:

    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
            sigset_t sigs;
    
            sigemptyset(&sigs);
            sigaddset(&sigs, SIGINT);
            sigprocmask(SIG_BLOCK, &sigs, 0);
    
            if (argc > 1) {
                    execvp(argv[1], argv + 1);
                    perror("execv");
            } else {
                    fprintf(stderr, "Usage: %s  [args...]\n", argv[0]);
            }
            return 1;
    }
    

    If you compile this program to noint, you would just execute ./noint ./y.

    As ephemient notes in comments, the signal disposition is also inherited, so you can have the wrapper ignore the signal instead of blocking it:

    #include 
    #include 
    #include 
    
    int main(int argc, char *argv[])
    {
            struct sigaction sa = { 0 };
    
            sa.sa_handler = SIG_IGN;
            sigaction(SIGINT, &sa, 0);
    
            if (argc > 1) {
                    execvp(argv[1], argv + 1);
                    perror("execv");
            } else {
                    fprintf(stderr, "Usage: %s  [args...]\n", argv[0]);
            }
            return 1;
    }
    

    (and of course for a belt-and-braces approach, you could do both).

提交回复
热议问题