Posted on 2014-11-25 11:06
kongkongzi 阅读(291)
评论(0) 编辑 收藏 引用 所属分类:
c++ programming
Linux:
调用socketpair,create a pair of connected sockets。
1 int g_notificationPipeFDs[2];
2
3 int getNotificationSendFD()
4 {
5 return g_notificationPipeFDs[0];
6 }
7
8 int getNotificationRecvFD()
9 {
10 return g_notificationPipeFDs[1];
11 }
12
13 void* LogicThreadFunc(void* args)
14 {
15 struct timeval timeout;
16 timeout.tv_sec = 3;
17 timeout.tv_usec = 0;
18
19 int value;
20
21 while (1)
22 {
23 int nfds = getNotificationRecvFD() + 1;
24 fd_set readfds;
25 FD_ZERO(&readfds);
26 FD_SET(getNotificationRecvFD(), &readfds);
27
28 int ret = select(nfds, &readfds, NULL, NULL, &timeout);
29 if (ret < 0)
30 {
31 perror("select");
32 break;
33 }
34 else if (0 == ret)
35 {
36 // timeout and do nothing.
37 }
38 else
39 {
40 while (1)
41 {
42 int len = recv(getNotificationRecvFD(), &value, sizeof(value), 0);
43 if (len > 0)
44 {
45 printf("Recv: %d\n", value);
46 }
47 else
48 {
49 break;
50 }
51 }
52 }
53 }
54
55 return NULL;
56 }
57
58
59
60 int main(int c, char **v)
61 {
62 if (socketpair(AF_LOCAL, SOCK_STREAM, 0, g_notificationPipeFDs) != 0)
63 {
64 perror("socketpair");
65 return -1;
66 }
67
68 pthread_t logicThreadId;
69 int ret = pthread_create(&logicThreadId, NULL, LogicThreadFunc, NULL);
70 if (ret != 0)
71 {
72 perror("fail to create thread 1.\n");
73 return -1;
74 }
75
76 int value;
77 while (1)
78 {
79 std::cin >> value;
80 printf("Input: %d\n", value);
81 int len = send(getNotificationSendFD(), &value, sizeof(value), 0);
82 if (len != sizeof(value))
83 {
84 printf("just send %d bytes.\n", len);
85 }
86 }
87
88 return 0;
89 }
参考 libevent的evutil_socketpair的实现。
/** Create two new sockets that are connected to each other.
On Unix, this simply calls socketpair(). On Windows, it uses the
loopback network interface on 127.0.0.1, and only
AF_INET,SOCK_STREAM are supported.
(This may fail on some Windows hosts where firewall software has cleverly
decided to keep 127.0.0.1 from talking to itself.)
Parameters and return values are as for socketpair()
*/
int evutil_socketpair(int d, int type, int protocol, evutil_socket_t sv[2]);
使用Socket实现进程间的通讯,与使用 “Mutex lock + Condition variable + 共享缓存区” 实现进程间的通讯的区别:
- Socket方式:为了实现异步非阻塞地触发处理事件,一般需要把Recv端的socket加入到一个Reactor或Proactor。数据需要被拷贝。
- Condition variable方式:在wait端需要死等,没有超时设置(?)。需要加锁。