Created
September 14, 2018 16:15
-
-
Save jeffersonRibeiro/1dd9832c7b799df761431427d12a1fba to your computer and use it in GitHub Desktop.
nonblock input in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdio.h> | |
// cc.byexamples.com calls this int kbhit(), to mirror the Windows console | |
// function of the same name. Otherwise, the code is the same. | |
bool inputAvailable() | |
{ | |
struct timeval tv; | |
fd_set fds; | |
tv.tv_sec = 0; | |
tv.tv_usec = 0; | |
FD_ZERO(&fds); | |
FD_SET(STDIN_FILENO, &fds); | |
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv); | |
return (FD_ISSET(0, &fds)); | |
} | |
int main(int argc, char* argv[]) | |
{ | |
std::string initialCommand; | |
if (argc > 1) { | |
// Code to get the initial command from a file | |
} else { | |
while (!inputAvailable()) { | |
std::cout << "Waiting for input (Ctrl-C to cancel)..." << std::endl; | |
sleep(1); | |
} | |
std::getline(std::cin, initialCommand); | |
} | |
// Start a thread class instance 'jobThread' to run the command | |
// Start a thread class instance 'inputThread' to look for further commands | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment