#include #include #include #include #include #include "io.h" /* global data */ static struct { int have_data; char buf[BUFSIZ]; } io_g = { 0 }; pthread_mutex_t mutex; static void * io_poll(void *arg) { char *s=(void*)1; while(s) { if(!io_g.have_data) { pthread_mutex_lock(&mutex); s = fgets(io_g.buf, BUFSIZ, stdin); if(s) { io_g.have_data = 1; } /* no error check! */ pthread_mutex_unlock(&mutex); } } return NULL; } static void init() { static int init_g = 0; pthread_t thread; if(!init_g) { pthread_mutex_init(&mutex, NULL); pthread_create(&thread, NULL, io_poll, NULL); init_g = 1; } } #define min(a,b) ((a)<(b)?(a):(b)) int asyncGetLine(char *buf, int buflen) { int len = 0; init(); if(io_g.have_data) { pthread_mutex_lock(&mutex); if(io_g.have_data) { len = min(buflen, BUFSIZ); memcpy(buf, io_g.buf, len); io_g.have_data = 0; } pthread_mutex_unlock(&mutex); } if(len) { return len; } else { return (feof(stdin) ? -1 : 0); } }