2012-01-27 14 views
2

我想監視一個unix套接字(「/ tmp/mysocket」)。C或C++與libevent/libev:監視一個unix套接字

我可以在Node.js中做到這一點:1)綁定套接字,2)有人連接到套接字,3)數據發送到套接字,4)套接字斷開。

我想現在在C/C++中執行此操作:我想監視上述事件的「/ tmp/mysocket」。我看過libevent(我最好喜歡使用),但看到它需要一個IP:端口。有沒有辦法監測unix套接字?

或者任何人都可以提出另一種C/C++解決方案嗎?

回答

5

您可以像常規文件一樣監視UNIX域套接字,因爲它可以像文件一樣操作。 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應該是相似的。

+0

嗨,非常感謝那些信息。的確非常有用。我會試着去編譯它。我對libev和/或libevent非常陌生,需要一點點努力來填充代碼並使其工作! – Eamorr 2012-01-27 10:11:23

+0

Hi KennyTM - eve_io_init(...)的第三個參數'socket'是什麼類型? – Eamorr 2012-01-27 10:49:27

+0

@Eamorr:'int'。請檢查文檔。 http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_io_code_is_this_file_descrip – kennytm 2012-01-27 12:32:05