Search code examples
cshellbash-trap

Trap command from C program?


I'd like to run a trap '' 2 command from a C program to prevent ctrl-c when the a.out is run.

#define TRAP "trap '' 2"

int     main()
{
    system(TRAP);

    ...
}

I can get it to work from a .sh file that also runs the program but I'd like everything to be in one .c file.

trap '' 2
cd /Users/me
./a.out

I then tried to make another .c file that runs the script then launch the first a.out as I thought that it was a timing issue the first time without success either...

How can I get it to work within a single a.out or is that even possible?


Solution

  • trap '' INT ignores SIGINT. Ignore dispositions are inherited to child processes, so:

    trap '' 2
    cd /Users/me
    ./a.out
    

    ignores SIGINT for what follows, but it can't work up the process hierarchy.

    Fortunately it's not super difficult to ignore SIGINT from C.

    #include <signal.h>
    int main()
    {
       //....
       signal(SIGINT,SIG_IGN); // `trap '' INT` in C
       //^should never fail unless the args are buggy
       //...
    }