2

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

我可以在 Node.js 中很好地做到这一点:当 1) 绑定套接字、2) 有人连接到套接字、3) 将数据发送到套接字和 4) 套接字断开连接时,它会引发一个事件。

我现在正尝试在 C/C++ 中执行此操作:我想监视“/tmp/mysocket”的上述事件。我查看了 libevent(我更喜欢使用它),但看到它需要一个 IP:端口。有什么方法可以监控 unix 套接字?

或者任何人都可以建议另一个 C/C++ 解决方案?

4

1 回答 1

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 应该是类似的。

于 2012-01-27T10:06:39.310 回答