Hide ^C pressing ctrl-c in C Hide ^C pressing ctrl-c in C shell shell

Hide ^C pressing ctrl-c in C


The ^C comes from the echo on the terminal driver in Linux

Here's an example program in C. It first disables saves the current settings, and registers an atexit handler to restore settings when the program exits, then disables echo on the terminal of standard input. Then it enters an infinite while loop. When you now type anything on the terminal, nothing is displayed, not even that ^C.

The trick that shells use is that they completely replace the input handling on the terminal, switching off the canonical input handling, and reading standard input one character at a time, and handling the echoing on their own - something that requires far more code than is possible in a Stack Overflow answer.

#include <termios.h>#include <unistd.h>#include <stdlib.h>struct termios saved;void restore(void) {    tcsetattr(STDIN_FILENO, TCSANOW, &saved);}int main() {    struct termios attributes;    tcgetattr(STDIN_FILENO, &saved);    atexit(restore);    tcgetattr(STDIN_FILENO, &attributes);    attributes.c_lflag &= ~ ECHO;    tcsetattr(STDIN_FILENO, TCSAFLUSH, &attributes);    printf("Entering the loop\n");    while(1) {};}


Running stty -echoctl should hide it. See man stty for more details.