views:

312

answers:

4

Is it possible to write a C program which works in XFCE's terminal until the user hits Esc-key? If yes, how?

+1  A: 

I would recommend you look into ncurses, an API which is typically used to implement that kind of keyboard-reading in terminal/console applications. There should be no need to do this in a platform-dependent manner.

unwind
A: 

Switch the terminal to the non-canonical mode

dmityugov
+1  A: 

The most simple solution is pressing 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" );
}
sambowry
+1  A: 

I think you're 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 for interactive use by a human being. There are better ways to handle software that must run for "months".

Andy Ross