1
程序關閉,我有以下libev代碼:C/libev:當事件被觸發
#include <ev.h>
#include <stdio.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <string.h>
#include <stdlib.h>
#include <sys/un.h>
#include <netinet/in.h>
ev_io stdin_watcher;
static void cb(EV_P_ ev_io *w, int revents){
puts ("hello");
//read file here - suggestion due to Ioan
#define BUF_LEN 10
char buf[BUF_LEN];
memset(buf,0,BUF_LEN);
int byte_read;
while((byte_read = recv(w->fd,buf,BUF_LEN-1,0)) > 0) {
printf("len: %i: %s",byte_read,buf);
memset(buf,0,BUF_LEN);
}
if(-1 == byte_read && EAGAIN != errno) {
perror("recv");
}
close(w->fd);
//ev_io_stop (EV_A_ w);
//ev_unloop (EV_A_ EVUNLOOP_ALL);
}
int main (void){
struct ev_loop *loop = ev_default_loop (0);
int len;
int sd;
sd=socket(AF_UNIX,SOCK_STREAM,0);
struct sockaddr_un address;
//memset(&address,0,sizeof(address));
address.sun_family=AF_UNIX;
strcpy(address.sun_path,"/tmp/mysocket");
unlink(address.sun_path);
len=strlen(address.sun_path)+sizeof(address.sun_family);
int x=bind(sd,(struct sockaddr*)&address,sizeof(address));
printf("%d\n",x);
listen(sd,5);
ev_io_init(&stdin_watcher,cb,sd,EV_READ);
ev_io_start(loop,&stdin_watcher);
ev_loop (loop, 0);
// unloop was called, so exit
return 0;
}
一切工作就好了(幾乎)。編譯:gcc file.c -lev
,並運行./a.out
。然後寫入./a.out
正在偵聽的套接字:echo "gobblydeegook" | nc -U /tmp/mysocket
。
Hello按預期出現在控制檯上。
但程序調用該事件,然後繼續打印「hello」ad-infinitum!我希望它繼續監視這個unix套接字的寫入。這個怎麼做?
嗯。這非常有趣,謝謝。我嘗試讀取數據(查看更新後的帖子,但我一直收到一個「recv:Invalid argument」錯誤 – Eamorr 2012-01-27 15:35:41
libev也在套接字上調用相同的事件來處理錯誤,就像它關閉時一樣。該事件再次被調用,此時,您嘗試在一個封閉的套接字上進行接收。 – Ioan 2012-01-27 15:39:57
oh right ...我認爲我瞭解你,你知道有什麼辦法可以抵制這個嗎? – Eamorr 2012-01-27 15:41:50