作者bombilla (地板別打我!>"<)
看板LinuxDev
標題[問題] select 與 eventfd
時間Fri May 17 13:44:02 2013
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;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 60.251.182.145
推 AceIan:read_handler 被沒有把東西 read 走啊 05/17 13:49
→ bombilla:啊?所以我一定要read走喔? 05/17 13:50
→ bombilla:我去試試~ =.=a 多謝~ 05/17 13:50
→ bombilla:等一下~~可是我不輸入任何值,只是在那邊等10秒鐘~ 05/17 13:52
→ bombilla:它也是會拼了命的印出 no data 說~ 05/17 13:52
我現在多加了 eventfd_read ,現在的動作:
1.我輸入一些字元,這些字元會被printf出來沒錯…每次我一輸入完,
select不就應該是要重算10秒嗎?但…就算我一直有輸入,
10秒一到還是一直噴no data…
2.程式執行起來10秒一到,就一直噴no data…
※ 編輯: bombilla 來自: 60.251.182.145 (05/17 15:11)
→ bombilla:好,我試了一下~~迴圈內也得每次重設tv~XD 05/17 15:23
每次select跳出來之後tv的值會被清成零~XD
※ 編輯: bombilla 來自: 60.251.182.145 (05/17 15:25)
→ okgogogo:FD_ISSET 05/24 21:19