Search code examples
c++terminalgetchar

Exit program if i get any char


i'm creating a program and i want to exit the program if i get any key pressed. So far i can only do that if the return is pressed, it happens, because the getch needs the return to be pressed.

Code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
static void * breakonret(void *instance);
int main(){
  pthread_t mthread;
  pthread_create(&mthread, NULL, breakonret, NULL);
  while(1){
    printf("Data on screen\n");
    sleep(1);
  }
}
static void * breakonret(void *instance){
  getchar();
  exit(0);
}

Solution

  • (I retagged the question from getch to getchar because they are two different things).

    As you noticed, getchar waits for a return to be pressed before returning. You need to use a different function if you want it to return as soon as any key is pressed. On Windows, there is a builtin function called getch() which does that, defined in <conio.h>. On POSIX platforms (e.g. Linux, OS X), there is no builtin getch(), but you can write your own version like this (from http://cboard.cprogramming.com/faq-board/27714-faq-there-getch-conio-equivalent-linux-unix.html):

    #include <termios.h>
    
    int getch( ) 
    {
      struct termios oldt,
                     newt;
      int            ch;
      tcgetattr( STDIN_FILENO, &oldt );
      newt = oldt;
      newt.c_lflag &= ~( ICANON | ECHO );
      tcsetattr( STDIN_FILENO, TCSANOW, &newt );
      ch = getchar();
      tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
      return ch;
    }