Kill CTRL+C!

Jul 22, 2008 at 5:48pm
Well, title says it all.

Is there any way at all that I can make some sort of hook (I guess I can call it that?) to remove the feature of quitting my program with CTRL+C?

Thanks.
Jul 22, 2008 at 8:27pm
To just toggle it on or off:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <termio.h>
#include <unistd.h>

void ctrlbrk( bool b )
  {
  struct termios settings;
  tcgetattr( STDIN_FILENO, &settings );
  if (b)
    {
    settings.c_iflag |=  BRKINT;
    settings.c_iflag &= ~IGNBRK;
    }
  else
    {
    settings.c_iflag &= ~BRKINT;
    settings.c_iflag |=  IGNBRK;
    }
  tcsetattr( STDIN_FILENO, TCSANOW, &settings );
  }

To turn it off: ctrlbrk( false );
To turn it on: ctrlbrk( true );

Be sure to turn it back on before your program terminates.

Oh, and if you are using C89, you'll have to change that 'bool' to 'int'.

Hope this helps.
Last edited on Jul 22, 2008 at 8:28pm
Jul 23, 2008 at 8:16am
I think CTRL+C send a SIGHUP, or maybe a SIGINT. Either way you can just mask it out or set the default action to ignore it.
Jul 25, 2008 at 5:11pm
yap, there is such a system call
result = signal(int signum, void(*action)(int))
<signal.h>

just use man signal
in signal.h all the possible signals are listed

//and there are some problems about how to restore the
//previous state of signal handling after a handle happened
//in some system the handle is set to default value

#include <stdio.h>
#include <signal.h>
main()
{
void f(int);
signal(SIGINT, f);
for (i = 0; i < 5; i++) {
printf("hello\n");
sleep(1);
}
}
void f(int signum)
{
printf("OUCH\n");
}

try to press Ctrl+C while "hello"
Jul 25, 2008 at 8:09pm
Both of those deal with catching the SIGINT signal. The OP doesn't want the signal generated in the first place. To do that, you have to modify the input stream's IGNBRK and BRKINT flags so that pressing ^C doesn't cause the input device to post a SIGINT.
Jul 25, 2008 at 10:14pm
I don't know whether the OP wants to stop the SIGINT at source or stop his program reacting to it.

If it's to stop the program reacting to it, I wouldn't recommend using signal(), it's the unreliable way of handling signals and bordering on depricated.

To ignore a signal in a single threaded program do something like this

1
2
3
4
5
6
7
8
9
10
11
12
#include <signal.h>

struct sigaction  act;
int result;

act.sa_handler = SIG_IGN;
act.sa_flags = NULL;
act.sa_mask = NULL;

result = sigaction(SIGINT, &act, NULL);


Topic archived. No new replies allowed.