c或c ++ with libevent / libev:监视UNIX套接字
题
我正在尝试监视UNIX套接字(“/ tmp / mysocket”)。
我可以在node.js中执行此精细:它提出了一个事件时1)绑定的套接字,2)有人连接到插座,3)数据被发送到套接字,4)套接字已断开连接。
我现在在c / c ++中执行此操作:我想为上述事件监控“/ tmp / mysocket”。我看过libevent(我最好用的人),但看到它需要IP:端口。有没有办法监控UNIX套接字?
或者任何人都可以建议另一个C / C ++解决方案?
解决方案
You could monitor a UNIX domain socket just like a regular file, since it can be operated like a file, e.g. in 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 should be similar.
不隶属于 StackOverflow