Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
vì thế nên Nhân Linux cần phải liên kết với những chương trình ứng dụng được viết bởi tổ chức GNU tạo lên 1 HĐH hoàn chỉnh: HĐH Linux. Đây cũng là lý do tại sao chúng ta thấy GNU/Linux khi được nhắc đến Linux. | 290 CHAPTER 7 printf Unable to accept s n strerror errno close listener return 1 We now have a live client. Print information about it and then send something over the wire. inet_ntop AF_INET sa.sin_addr dotted_ip 15 printf Received connection from s. n dotted_ip Use popen to retrieve the output of the uptime command. This is a bit of a hack but it s portable and it works fairly well. popen opens a pipe to a program that is it executes the program and redirects its I O to a file handle . uptime popen usr bin uptime r if uptime NULL strcpy sendbuf Unable to read system s uptime. n else sendbuf 0 0 fgets sendbuf 1023 uptime pclose uptime Figure out how much data we need to send. length strlen sendbuf sent 0 Repeatedly call write until the entire buffer is sent. while sent length int amt amt write client sendbuf sent length-sent if amt 0 Zero-byte writes are OK if they are caused by signals EINTR . Otherwise they mean the socket has been closed. NETWORKED GAMING WITH LINUX 291 if errno EINTR continue else printf Send error s n strerror errno break Update our position by the number of bytes that were sent. sent amt close client return 0 Our server starts by creating a socket and binding it to a local port. It specifies INADDR_ANY for an address since we don t have any particular network interface in mind. You could use this to bind the socket to just one particular IP address in a multihomed system but games usually don t need to worry about this. It then uses listen to set the socket up as a listener with a connection queue of five clients. Next comes the accept loop in which the server actually receives and processes incoming connections. It processes one client for each iteration of the loop. Each client gets a copy of the output of the Linux uptime program. Note the use of popen to create this pipe. The server uses a simple write loop to send this data to the client. If you feel adventurous you might try modifying this program to deal with multiline output for .