1
+ #include " local.h"
2
+ #include " utils.h"
3
+
4
+ using namespace std ;
5
+
6
+ char message[BUF_SIZE];
7
+
8
+ /*
9
+ 流程:
10
+ 调用fork产生两个进程,两个进程通过管道进行通信
11
+ 子进程:等待客户输入,并将客户输入的信息通过管道写给父进程
12
+ 父进程:接受服务器的信息并显示,将从子进程接受到的信息发送给服务器
13
+ */
14
+ int main (int argc, char *argv[])
15
+ {
16
+ int sock, pid, pipe_fd[2 ], epfd;
17
+
18
+ struct sockaddr_in addr;
19
+ addr.sin_family = PF_INET;
20
+ addr.sin_port = htons (SERVER_PORT);
21
+ addr.sin_addr .s_addr = inet_addr (SERVER_HOST);
22
+
23
+ static struct epoll_event ev, events[2 ];
24
+ ev.events = EPOLLIN | EPOLLET;
25
+
26
+ // 退出标志
27
+ int continue_to_work = 1 ;
28
+
29
+ CHK2 (sock,socket (PF_INET, SOCK_STREAM, 0 ));
30
+ CHK (connect (sock, (struct sockaddr *)&addr, sizeof (addr)) < 0 );
31
+
32
+ CHK (pipe (pipe_fd));
33
+
34
+ CHK2 (epfd,epoll_create (EPOLL_SIZE));
35
+
36
+ ev.data .fd = sock;
37
+ CHK (epoll_ctl (epfd, EPOLL_CTL_ADD, sock, &ev));
38
+
39
+ ev.data .fd = pipe_fd[0 ];
40
+ CHK (epoll_ctl (epfd, EPOLL_CTL_ADD, pipe_fd[0 ], &ev));
41
+
42
+ // 调用fork产生两个进程
43
+ CHK2 (pid,fork ());
44
+ switch (pid)
45
+ {
46
+ case 0 : // 子进程
47
+ close (pipe_fd[0 ]); // 关闭读端
48
+ printf (" Enter 'exit' to exit\n " );
49
+ while (continue_to_work)
50
+ {
51
+ bzero (&message, BUF_SIZE);
52
+ fgets (message, BUF_SIZE, stdin);
53
+
54
+ // 当收到exit命令时,退出
55
+ if (strncasecmp (message, CMD_EXIT, strlen (CMD_EXIT)) == 0 )
56
+ {
57
+ continue_to_work = 0 ;
58
+ }
59
+ else
60
+ {
61
+ CHK (write (pipe_fd[1 ], message, strlen (message) - 1 ));
62
+ }
63
+ }
64
+ break ;
65
+ default : // 父进程
66
+ close (pipe_fd[1 ]); // 关闭写端
67
+ int epoll_events_count, res;
68
+ while (continue_to_work)
69
+ {
70
+ CHK2 (epoll_events_count,epoll_wait (epfd, events, 2 , EPOLL_RUN_TIMEOUT));
71
+
72
+ for (int i = 0 ; i < epoll_events_count ; i++)
73
+ {
74
+ bzero (&message, BUF_SIZE);
75
+ if (events[i].data .fd == sock) // 从服务器接受信息
76
+ {
77
+ CHK2 (res,recv (sock, message, BUF_SIZE, 0 ));
78
+ if (res == 0 ) // 服务器已关闭
79
+ {
80
+ CHK (close (sock));
81
+ continue_to_work = 0 ;
82
+ }
83
+ else
84
+ {
85
+ printf (" %s\n " , message);
86
+ }
87
+ }
88
+ else // 从子进程接受信息
89
+ {
90
+ CHK2 (res, read (events[i].data .fd , message, BUF_SIZE));
91
+ if (res == 0 )
92
+ {
93
+ continue_to_work = 0 ;
94
+ }
95
+ else
96
+ {
97
+ CHK (send (sock, message, BUF_SIZE, 0 ));
98
+ }
99
+ }
100
+ }
101
+ }
102
+ }
103
+ if (pid)
104
+ {
105
+ close (pipe_fd[0 ]);
106
+ close (sock);
107
+ }else
108
+ {
109
+ close (pipe_fd[1 ]);
110
+ }
111
+
112
+ return 0 ;
113
+ }
0 commit comments