Linux console keyboard handler

Is it possible to write a C program that runs on the XFCE terminal until the user hits the Esc key? If so, how?

+2


source to share


4 answers


I would recommend that you learn ncurses , an API that is commonly used to implement this kind of keyboard reading in terminal / console applications. It shouldn't be necessary to do this depending on the platform.



+1


source


The simplest solution is to press Ctrl-C in the terminal window. Your application will stop immediately, or you can handle the event with a SIGINT signal handler.



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

volatile int exit_loop;

void sig_hnd( void ){ exit_loop=1; }

int main(void){
  signal( SIGINT, (void (*)(int))sig_hnd );

  for( exit_loop=0; !exit_loop; ){
    puts( "do some work" );
    sleep(1);
  }

  puts( "\nend of work\n" );
}

      

+1


source


I think you are asking the wrong question. Why are you using an interactive terminal at all for a long running process? Why not just run as a daemon and log the "best" solution at regular intervals? The terminal is intended for interactive human use. There are better ways to handle software that should run for "months".

+1


source


Switch terminal to non-canon mode

0


source







All Articles