简体   繁体   中英

Ignoring ctrl-c

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

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 Ctrl C , here is what I get:

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

but I want:

myshell>
myshell>
myshell>

Here is my code relevant to Ctrl C :

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

main()
{
    sigset( SIGINT, disp );
    while(1)
    {
        Command::_currentCommand.prompt();
        yyparse();
    }
}

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.

尝试打印退格字符,又名\\ b?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM