I’m trying to peek stdin to see if anything is there using pthreads. I (think I) need to do this because if there is nothing in std in, stream access functions will block for input.
I feel the way to do this is to fire off a pthread that checks stdin, and sleep(1) and see if the thread found anything.
Here’s what I have so far. If nothing is piped into the program then it will sleep as expected, but if something is in stdin the thread never gets fired.
#include <iostream>
#include <pthread.h>
#include <stdlib.h>
using namespace std;
void *checkStdIn(void *d){
char c = '\0';
c = cin.peek();
if (c){
cout << c << endl;
}
}
int main(int argc, char *argv[]){
pthread_t thread;
int rc;
rc = pthread_create(&thread, NULL, checkStdIn, NULL);
if (rc){
cerr << "Error no. " << rc << endl;
exit(EXIT_FAILURE);
}
sleep(2);
return 0;
}
You don’t need pthreads for that and you can use
select(2)orpoll(2)to known if you can peek the stdin without blocking your application. For that I coded themy_peek()function which you just need to pass the number of seconds you want to wait for the input (you can even pass 0 if you don’t want to wait):Please note that it is BAD to rely on
select(2)to tell if there is data in thecinobject orstdinFILEstructure because, as Nemo stated, they are BUFFERED. The best thing to do is avoid “cin” in this example usingread(2). The improved version ofmy_peek()would look like:For more information please check the
select(2)manual page at http://linux.die.net/man/2/select.PS: You could try to rely on the value returned by the
std::cin.rdbuf()->in_avail()as explained in the cpluplus site http://www.cplusplus.com/reference/iostream/streambuf/in_avail/, or even in thereadsome()method of theistreamclass, but they usually depend on theFILEbuffer which is not exposed in the GNU C++ library. Don’t do it or you might fail.