chonglawr
chonglawr

Reputation: 211

How can I detect different control signals?

In my program, I want to detect when a user presses ctrl + a,b,c,d,e... with different actions for each character. I have :

int main(){
    signal(SIGINT, sighandler);
    while(1) {
      sleep(1); 
    }
    return(0);
}

void sighandler(int signum){
   printf("Caught signal %d, coming out...\n", signum);
   exit(1);
}

I'd like to control what the ctrl+chars do but currently only ctrl+c is being detected, how can I detect the other characters too?

Upvotes: 0

Views: 68

Answers (1)

Nominal Animal
Nominal Animal

Reputation: 39366

No. Ctrl+C is not a "control signal".

In POSIX systems, terminals have three keypresses that cause the kernel to send a signal the process reading from the terminal: Ctrl+C for interrupt (SIGINT), Ctrl+\ for quit (SIGQUIT), Ctrl+Z for suspend (SIGTSTP). You can override the keypresses to just about any Ctrl+key combination using the POSIX termios interface -- but remember, there are only three (signals and possible keypresses).

It is much more common to use the termios interface (or equivalently the stty command in scripts) to put the terminal into raw mode, in which case the application gets all keypresses not consumed by the kernel or graphical user interface (key combinations reserved for stuff like switching terminals, closing windows, and so on).

The most portable way to do this is to use a very common library called Curses. The most common implementation (that has a few extra goodies compared to plain Curses) is ncurses -- no need to go to that link to download and compile the sources; the library is already packaged for your distribution, so you can find it in the standard software repositories. For Windows, there is PDCurses; with MinGW compiler, you can also use ncurses in Windows, too.

Do not be fooled about the ages of various versions of the library (although I do recommend ncurses 6 if you can utilize it); the curses interface is stable, and been used for a very long time. Ncurses does add some useful stuff, and is actively maintained still.

Upvotes: 1

Related Questions