4

I'm trying to write a shell and I'm at the point where I want to ignore CtrlC.

I currently have my program ignoring SIGINT and printing a new line when the signal comes, but how can I prevent the ^C from being printed?

When pressing CtrlC, here is what I get:

myshell>^C
myshell>^C
myshell>^C

but I want:

myshell>
myshell>
myshell>

Here is my code relevant to CtrlC:

extern "C" void disp( int sig )
{
    printf("\n");
}

main()
{
    sigset( SIGINT, disp );
    while(1)
    {
        Command::_currentCommand.prompt();
        yyparse();
    }
}
udondan
  • 57,263
  • 20
  • 190
  • 175
samoz
  • 56,849
  • 55
  • 141
  • 195

2 Answers2

12

It's the terminal that does echo that thing. You have to tell it to stop doing that. My manpage of stty says

* [-]ctlecho
       echo control characters in hat notation (`^c')

running strace stty ctlecho shows

ioctl(0, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0
ioctl(0, SNDCTL_TMR_STOP or TCSETSW, {B38400 opost isig icanon echo ...}) = 0
ioctl(0, SNDCTL_TMR_TIMEBASE or TCGETS, {B38400 opost isig icanon echo ...}) = 0

So running ioctl with the right parameters could switch that control echo off. Look into man termios for a convenient interface to those. It's easy to use them

#include <termios.h>
#include <unistd.h>
#include <stdio.h>

void setup_term(void) {
    struct termios t;
    tcgetattr(0, &t);
    t.c_lflag &= ~ECHOCTL;
    tcsetattr(0, TCSANOW, &t);
}

int main() {
    setup_term();
    getchar();
}

Alternatively, you can consider using GNU readline to read a line of input. As far as i know, it has options to stop the terminal doing that sort of stuff.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
0

Try printing the backspace character, aka \b ?

Ian Kelling
  • 9,643
  • 9
  • 35
  • 39