Hi all,
我有點問題想請教一下,就是我想弄一個consumer和producer的測試~
所以我先弄eventfd弄了一個fd然後再開一個thread,在這個thread中
使用select去聽這個fd。
但問題是select只能block住第一次,接著就再也不會block住了,
如果我有keyin東西的話就是拼命印出buffer的值,
不然就是時間一到就拼命印出no data…
感謝各位~
我測試的程式碼如下:
static char buffer[128] = { 0 };
static void *read_handler(void *arg)
{
int fd = *((int *)arg);
int ret = 0;
fd_set rfds;
struct timeval tv;
eventfd_t r;
//tv.tv_sec = 10;
//tv.tv_usec = 0;
while(1) {
tv.tv_sec = 10;
tv.tv_usec = 0;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
ret = select(fd + 1, &rfds, NULL, NULL, &tv);
if (ret == -1)
printf("select error...%d\n", ret);
else if (ret) {
printf("[%s]\n", buffer);
if ((strncmp(buffer, "quit", 4) == 0)) break;
eventfd_read(fd, &r);
} else
printf("no data\n");
}
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t read_thd;
int fd = eventfd(0, 0);
char ch = 0;
void *res = NULL;
unsigned long long no = 1;
if (pthread_create(&read_thd, NULL, &read_handler, &fd)) {
printf("pthread_create failed...\n");
return -1;
}
do {
printf("Enter string: ");
scanf("%s", buffer);
eventfd_write(fd, no);
} while (strncmp(buffer, "quit", 4));
pthread_join(read_thd, &res);
if (res) free(res);
close(fd);
return 0;
}