C / libev:程序在触发事件时关闭

时间:2012-01-27 13:55:15

标签: c events sockets 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;
}

一切都很好(几乎)。编译:{{1​​}},然后运行gcc file.c -lev。然后写入./a.out正在监听的套接字:./a.out

Hello会按预期显示在控制台上。

但该程序调用该事件,然后它继续打印“hello”ad-infinitum!我希望它继续监视这个unix socket以进行写入。怎么做?

1 个答案:

答案 0 :(得分:2)

当要在套接字上读取数据时,将调用该事件。由于您没有从套接字中删除数据,只需打印“hello”,再次调用该事件来处理数据。