带有libevent / libev的C或C ++:监视一个unix套接字

时间:2012-01-27 09:40:52

标签: c++ c libevent libev

我正在尝试监控unix套接字(“/ tmp / mysocket”)。

我可以在Node.js中做得很好:当1)套接字被绑定,2)某人连接到套接字,3)数据被发送到套接字并且4)套接字被断开时,它引发一个事件。 / p>

我现在尝试在C / C ++中执行此操作:我想监视上述事件的“/ tmp / mysocket”。我看过libevent(我最好喜欢使用),但是看到它需要一个IP:端口。有没有办法监控unix套接字?

或者任何人都可以提出另一种C / C ++解决方案吗?

1 个答案:

答案 0 :(得分:5)

您可以像常规文件一样监视UNIX域套接字,因为它可以像文件一样操作,例如在libev中,

struct sockaddr_un address;
memset(&address, 0, sizeof(address));
address.sun_family = AF_LOCAL;
strcpy(address.sun_path, "/tmp/mysocket");

bind(socket, (struct sockaddr*)(&address), sizeof(address));
listen(socket, 5);

// now listen if someone has connected to the socket.
// we use 'ev_io' since the 'socket' can be treated as a file descriptor.
struct ev_io* io = malloc(sizeof(ev_io));
ev_io_init(io, accept_cb, socket, EV_READ);
ev_io_start(loop, io);
...

void accept_cb(struct ev_loop* loop, struct ev_io* io, int r)
{
    // someone has connected. we accept the child.
    struct sockaddr_un client_address;
    socklen_t client_address_len = sizeof(client_address);
    int client_fd = accept(socket, (sockaddr*)(&client_address),
                           &client_address_len);

    // 'read' / 'recv' from client_fd here.
    // or use another 'ev_io' for async read.
}

libevent应该是相似的。