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);
}
(I retagged the question from
getchtogetcharbecause they are two different things).As you noticed,
getcharwaits 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 calledgetch()which does that, defined in<conio.h>. On POSIX platforms (e.g. Linux, OS X), there is no builtingetch(), 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):