Ctrl + C Interrupt Event Handling in Linux

Ctrl + C interrupt event handling in Linux

When you press Ctr + C, the operating system sends a signal to the process. There are many signals and one of them is SIGINT. The SIGINT ("program interrupt") is one of the Termination Signals.

There are a few more kinds of Termination Signals, but the interesting thing about SIGINT is that it can be handled (caught) by your program. The default action of SIGINT is program termination. That is, if your program doesn't specifically handle this signal, when you press Ctr + C your program terminates as the default action.

To change the default action of a signal you have to register the signal to be caught. To register a signal in a C program (at least under POSIX systems) there are two functions

  1. signal(int signum, sighandler_t handler);
  2. sigaction(int signum, const struct sigaction *act,
    struct sigaction *oldact);.

These functions require the header signal.h to be included in your C code. I have provide a simple example of the signal function below with comments.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h> // our new library
volatile sig_atomic_t flag = 0;
void my_function(int sig){ // can be called asynchronously
flag = 1; // set flag
}

int main(){
// Register signals
signal(SIGINT, my_function);
// ^ ^
// Which-Signal |-- which user defined function registered
while(1)
if(flag){ // my action when signal set it 1
printf("\n Signal caught!\n");
printf("\n default action it not termination!\n");
flag = 0;
}
return 0;
}

Note: you should only call safe/authorized functions in signal handler. For example avoid calling printf in signal handler.

You can compile this code with gcc and execute it from the shell. There is an infinite loop in the code and it will run until you send a SIGINT signal by pressing Ctr + C.

How can I catch a ctrl-c event?

signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void my_handler(int s){
printf("Caught signal %d\n",s);
exit(1);

}

int main(int argc,char** argv)
{

struct sigaction sigIntHandler;

sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;

sigaction(SIGINT, &sigIntHandler, NULL);

pause();

return 0;
}

My shell cannot prevent ctrl+c from killing itself

I wonder why ash or other bash could work, so dig into ash's source code. I try this snippets.

It works.

    int ofd;
ofd = fd = open(_PATH_TTY, O_RDWR);
if (fd < 0) {
/* BTW, bash will try to open(ttyname(0)) if open("/dev/tty") fails.
* That sometimes helps to acquire controlling tty.
* Obviously, a workaround for bugs when someone
* failed to provide a controlling tty to bash! :) */
fd = 2;
while (!isatty(fd))
if (--fd < 0)
goto out;
}
/* fd is a tty at this point */
fd = fcntl(fd, F_DUPFD, 10);
if (ofd >= 0) /* if it is "/dev/tty", close. If 0/1/2, dont */
close(ofd);
if (fd < 0)
goto out; /* F_DUPFD failed */
close_on_exec_on(fd);
while (1) { /* while we are in the background */
pgrp = tcgetpgrp(fd);
if (pgrp < 0) {
out:
ash_msg("can't access tty; job control turned off");
mflag = on = 0;
goto close;
}
if (pgrp == getpgrp())
break;
killpg(0, SIGTTIN);
}
initialpgrp = pgrp;

setsignal(SIGTSTP);
setsignal(SIGTTOU);
setsignal(SIGTTIN);
pgrp = rootpid;
setpgid(0, pgrp);
xtcsetpgrp(fd, pgrp);

Why Linux always output ^C upon pressing of Ctrl+C?

It is the terminal (driver) that intercepts the ^C and translates it to a signal sent to the attached process (which is the shell) stty intr ^B would instruct the terminal driver to intercept a ^B instead. It is also the terminal driver that echoes the ^C back to the terminal.

The shell is just a process that sits at the other end of the line, and receives it's stdin from your terminal via the terminal driver (such as /dev/ttyX), and it's stdout (and stderr) are also attached to the same tty.

Note that (if echoing is enabled) the terminal sends the keystrokes to both the process (group) and back to the terminal. The stty command is just wrapper around the ioctl()s for the tty driver for the processes "controlling" tty.

UPDATE: to demonstrate that the shell is not involved, I created the following small program. It should be executed by its parent shell via exec ./a.out (it appears an interactive shell will fork a daughter shell, anyway) The program sets the key that generates the SIGINTR to ^B, switches echo off, and than waits for input from stdin.

#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

int thesignum = 0;
void handler(int signum);

void handler(int signum)
{ thesignum = signum;}

#define THE_KEY 2 /* ^B */

int main(void)
{
int rc;
struct termios mytermios;

rc = tcgetattr(0 , &mytermios);
printf("tcgetattr=%d\n", rc );

mytermios.c_cc[VINTR] = THE_KEY; /* set intr to ^B */
mytermios.c_lflag &= ~ECHO ; /* Dont echo */
rc = tcsetattr(0 , TCSANOW, &mytermios);
printf("tcsetattr(intr,%d) =%d\n", THE_KEY, rc );

printf("Setting handler()\n" );
signal(SIGINT, handler);

printf("entering pause()\n... type something followed by ^%c\n", '@'+THE_KEY );
rc = pause();
printf("Rc=%d: %d(%s), signum=%d\n", rc, errno , strerror(errno), thesignum );

// mytermios.c_cc[VINTR] = 3; /* reset intr to ^C */
mytermios.c_lflag |= ECHO ; /* Do echo */
rc = tcsetattr(0 , TCSANOW, &mytermios);
printf("tcsetattr(intr,%d) =%d\n", THE_KEY, rc );

return 0;
}

intr.sh:

#!/bin/sh
echo $$
exec ./a.out
echo I am back.

Is the abrupt ending of a process using Control + C a trap or an interrupt?

The difference between a trap and an interrupt is not as you described in your question (thanks for the reference) but to the asynchronous nature of the events producing it. A trap means an interrupt in the code execution due to a normally incorrect/internal operation (like dividing by zero or a page fault, or as you signaled, a software interrupt), but it ocurrs always at the same place in the code (synchronously with the code execution) and an interrupt occurs because of external hardware, when some device signals the cpu to interrupt what it is doing, as it's ready to send some data. By nature, traps are synchronous and interrupts aren't.

Said this, both are anomalous events that change the normal course of execution of the cpu. Both are hardware produced, but for different reasons: the first occurs synchronously (you know always when, in which instruction, it will be produced, if produced at all) and the second not (you don't know in advance which instruction will be executing when external hardware would assert the interrupt line) Also, there are two kinds of traps (depending on the event that triggered them), one puts the instruction pointer pointing to the next instruction (for example a divide by zero trap) to be executed, and the other puts it pointing to the same instruction that caused the trap (for example a page fault, that has to be reexecuted once the cause of the trap has been corrected) Of course, software interrupts, as by their nature, are always traps (traps that always change the course of execution) as it can be predicted the exact point in the program flow where the cpu will get interrupted.

So, with this explanation, you probably can answer your question yourshelf, a Ctrl-C interrupt is an interrupt as you cannot predice in advance when it will interrupt the cpu execution and you cannot mark that point in your code.

Remember, interrupts ocurr asynchronously, traps not.

How does Ctrl-C terminate a child process?

Signals by default are handled by the kernel. Old Unix systems had 15 signals; now they have more. You can check </usr/include/signal.h> (or kill -l). CTRL+C is the signal with name SIGINT.

The default action for handling each signal is defined in the kernel too, and usually it terminates the process that received the signal.

All signals (but SIGKILL) can be handled by program.

And this is what the shell does:

  • When the shell running in interactive mode, it has a special signal handling for this mode.
  • When you run a program, for example find, the shell:

    • forks itself
    • and for the child set the default signal handling
    • replace the child with the given command (e.g. with find)
    • when you press CTRL+C, parent shell handle this signal but the child will receive it - with the default action - terminate. (the child can implement signal handling too)

You can trap signals in your shell script too...

And you can set signal handling for your interactive shell too, try enter this at the top of you ~/.profile. (Ensure than you're a already logged in and test it with another terminal - you can lock out yourself)

trap 'echo "Dont do this"' 2

Now, every time you press CTRL+C in your shell, it will print a message. Don't forget to remove the line!

If interested, you can check the plain old /bin/sh signal handling in the source code here.

At the above there were some misinformations in the comments (now deleted), so if someone interested here is a very nice link - how the signal handling works.

Have ctrl+c interrupt a blocking system call

There's no getting around the fact that you need to know what you're interrupting, and that the code has to be designed to be interrupted.

In the particular example you've chosen, replace the sleep with a timed wait on an event. You can then interrupt it by setting the event.

If you're making a synchronous I/O call, you can use CancelSynchronousIo but of course the code handling the I/O then has to properly handle the cancellation.

If you're in an alertable wait you can queue an APC to the thread.

If you're in a message loop you can post a message or have the loop use MsgWaitForMultipleObjectsEx.

Additional: demo code showing demonstrating how to wake SleepEx

#include <Windows.h>
#include <stdio.h>
#include <tchar.h>

HANDLE mainthread;

VOID CALLBACK DummyAPCProc(
_In_ ULONG_PTR dwParam
)
{
printf("User APC\n");
return;
}

void SleepIntr()
{
printf("Entering sleep...\n");
SleepEx(10000, TRUE);
printf("Sleep done...\n");
}

static BOOL WINAPI ctrl_handler(DWORD dwCtrlType) {
printf("ctrl_handler pressed\n");
// Wake program up!
if (!QueueUserAPC(DummyAPCProc, mainthread, NULL))
{
printf("QueueUserAPC: %u\n", GetLastError());
return TRUE;
}
return TRUE;
}

int _tmain(int argc, _TCHAR* argv[])
{
if (!DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &mainthread, GENERIC_ALL, FALSE, 0))
{
printf("DuplicateHandle: %u\n", GetLastError());
return 0;
}

SetConsoleCtrlHandler(ctrl_handler, TRUE);
SleepIntr();
printf("awake!\n");
return 0;
}

CTRL+C not handled in python script when using su

The su command creates a new interactive shell and executes the command inside it.
When you use option -c (--command) the su command creates a new session with the user indicated in the command. To solve this use the option --session-command.
In this case the command will be this:

su user_name --session-command 'python myprogram.py <args>'

in this case you should be able to catch CTRL+C interrupt.



Related Topics



Leave a reply



Submit