Using a SIGINT from Ctrl+C
Asked Answered
A

3

6

alright, so i'm using a sighandler to interpret some signal, for this purpose it is Ctrl+C, so when Ctrl+C is typed some action will be taken, and everything is fine and dandy, but what I really need is for this to happen without ^C appearing in the input/output

for example let's say i have this code

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

void siginthandler(int param)
{
  printf("User pressed Ctrl+C\n");
  exit(1);
}

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

the output would be

^CUser pressed Ctrl+C

How could I get this to simply be

User pressed Ctrl+C?

Ahn answered 17/11, 2010 at 3:47 Comment(2)
Note that the ^C isn't actually in the output. Redirect the output of your program to a file with >output and observe that the ^C still appears in your terminal window, but does not appear in the output file.Balanchine
thanks so much for the help all, very good suggestions! i now consider myself a better programmer :)Ahn
B
3

You can achieve this effect using the curses library's "noecho()" call -- but you must be willing to accept (and/or use) curses terminal handling too ...

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

#include <curses.h>

void siginthandler(int param)
{
  endwin();
  printf("User pressed Ctrl+C\n");
  exit(1);
}

int main()
{
  initscr();
      noecho();
  signal(SIGINT, siginthandler);
  while(1);
  return 0;
}
Balanchine answered 17/11, 2010 at 4:8 Comment(1)
On closer inspection -- the ^C doesn't appear even without the noecho() call. Perhpas curses initscr() sets up this behavior by default.Balanchine
P
1

That is most likely not your program doing that. It's likely to be the terminal drivers, in which case you should look into stty with the ctlecho or echoctl options.

You can use stty -a to get all the current settings for your terminal device. For a programmatic interface to these items, termios is the way to go.

Paramnesia answered 17/11, 2010 at 4:3 Comment(1)
alright, that makes sense, thanks. how would i implement that in my code though? is it a C command, research is kinda sparse on it...Ahn
S
0

As other have said, this kind of thing falls under the control of your terminal driver and is typically done using the curses library. That said, here is a hack that will probably get you on your way:

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

void siginthandler(int param) {
    printf("User pressed Ctrl+C\n");
    system("stty echo");
    exit(1);
}

int main() {
    system("stty -echo");
    signal(SIGINT, siginthandler);
    while(1);
    return 0;
}
Sullins answered 17/11, 2010 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.