0

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?

Wizzardzz
  • 781
  • 1
  • 9
  • 32
  • 3
    The `trap` command is built into the shell itself, and only affects the currently running shell, and no other process. If you want to prevent `Ctrl-C` from breaking your program (usually a bad idea) then look into *signals* and `SIGBREAK`. – Some programmer dude Dec 29 '18 at 10:49

1 Answers1

1

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
   //...
}
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142