SHOW:
|
|
- or go back to the newest paste.
| 1 | #include <iostream> | |
| 2 | #include <cstdlib> | |
| 3 | #include <time.h> | |
| 4 | #include <thread> | |
| 5 | #include <curses.h> | |
| 6 | #include <termios.h> | |
| 7 | ||
| 8 | void SleepForNumberOfSeconds(const int & numberofSeconds,bool & timesUp); | |
| 9 | void WaitForTimeoutOrInterrupt(int const& numberofSeconds); | |
| 10 | int keypress(void); | |
| 11 | void nonblock(const bool state); | |
| 12 | ||
| 13 | int main(){
| |
| 14 | ||
| 15 | - | std::cout << "waiting a for 3 seconds or until a key is pressed" << std::endl; |
| 15 | + | std::cout << "waiting for 3 seconds or until a key is pressed" << std::endl; |
| 16 | WaitForTimeoutOrInterrupt(3); | |
| 17 | ||
| 18 | return EXIT_SUCCESS; | |
| 19 | } | |
| 20 | ||
| 21 | void SleepForNumberOfSeconds(const int & numberofSeconds,bool & timesUp){
| |
| 22 | ||
| 23 | timespec delay = {numberofSeconds,0}; //500,000 = 1/2 milliseconds
| |
| 24 | timespec delayrem; | |
| 25 | ||
| 26 | nanosleep(&delay, &delayrem); | |
| 27 | timesUp = true; | |
| 28 | ||
| 29 | return; | |
| 30 | } | |
| 31 | void WaitForTimeoutOrInterrupt(int const& numberofSeconds){
| |
| 32 | ||
| 33 | bool timesUp = false; | |
| 34 | ||
| 35 | std::thread t(SleepForNumberOfSeconds, numberofSeconds, std::ref(timesUp)); | |
| 36 | nonblock(1); | |
| 37 | while (!timesUp && !keypress()){
| |
| 38 | ||
| 39 | } | |
| 40 | ||
| 41 | if (t.joinable()){
| |
| 42 | t.detach(); | |
| 43 | } | |
| 44 | nonblock(0); | |
| 45 | ||
| 46 | return; | |
| 47 | } | |
| 48 | int keypress(void){
| |
| 49 | struct timeval tv; | |
| 50 | fd_set fds; | |
| 51 | tv.tv_sec = 0; | |
| 52 | tv.tv_usec = 0; | |
| 53 | FD_ZERO(&fds); | |
| 54 | FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0 | |
| 55 | select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); | |
| 56 | return FD_ISSET(STDIN_FILENO, &fds); | |
| 57 | } | |
| 58 | void nonblock(const bool state){
| |
| 59 | ||
| 60 | struct termios ttystate; | |
| 61 | ||
| 62 | //get the terminal state | |
| 63 | tcgetattr(STDIN_FILENO, &ttystate); | |
| 64 | ||
| 65 | if (state){
| |
| 66 | //turn off canonical mode | |
| 67 | ttystate.c_lflag &= ~ICANON; | |
| 68 | //minimum of number input read. | |
| 69 | ttystate.c_cc[VMIN] = 1; | |
| 70 | } | |
| 71 | else{
| |
| 72 | //turn on canonical mode | |
| 73 | ttystate.c_lflag |= ICANON; | |
| 74 | } | |
| 75 | ||
| 76 | //set the terminal attributes. | |
| 77 | tcsetattr(STDIN_FILENO, TCSANOW, &ttystate); | |
| 78 | } |