libevent / libev가있는 C 또는 C ++ : UNIX 소켓 모니터링
문제
UNIX 소켓을 모니터하려고합니다 ( "/ tmp / mysocket").
node.js 에서이 방법을 수행 할 수 있습니다. 1) 소켓이 바인딩 될 때 이벤트를 발생시키고, 2) 소켓에 연결되는 사람, 3) 데이터가 소켓에 전송되고 4) 소켓이 연결이 끊어졌습니다./ P>
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