C / LIBEV : 이벤트가 트리거되면 프로그램이 닫힙니다.
문제
다음 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"광고 - Infinitum을 인쇄합니다!쓰기를 위해이 UNIX 소켓을 계속 모니터링하기를 원합니다.이 작업을 수행하는 방법?
해결책
The event gets called when there is data to be read on the socket. Since you aren't removing the data from the socket, just printing "hello", the event is called again for you to handle the data.
제휴하지 않습니다 StackOverflow