#include #include #include #define STDIN 0 /* file descriptor for standard input */ main() { struct timeval tv; fd_set readfds; tv.tv_sec = 2; tv.tv_usec = 500000; FD_ZERO(&readfds); FD_SET(STDIN, &readfds); /* don't care about writefds and exceptfds: */ select(STDIN+1, &readfds, NULL, NULL, &tv); if (FD_ISSET(STDIN, &readfds)) printf("A key was pressed!/n"); else printf("Timed out./n"); } 假如你是在一个 line buffered 终端上,那么你敲的键应该是回车 (RETURN),否则无论如何它都会超时。 现在,你可能回认为这就是在数据报套接字上等待数据的方式--你是对 的:它可能是。有些 Unix 系统可以按这种方式,而另外一些则不能。你 在尝试以前可能要先看看本系统的 man page 了。 最后一件关于 select() 的事情:假如你有一个正在侦听 (listen()) 的套 接字,你可以通过将该套接字的文件描述符加入到 readfds 集合中来看是 否有新的连接。 这就是我关于函数select() 要讲的所有的东西。 参考书目: Internetworking with TCP/IP, volumes I-III by Douglas E. Comer and David L. Stevens. Published by Prentice Hall. Second edition ISBNs: 0-13-468505-9, 0-13-472242-6, 0-13-474222-2. There is a third edition of this set which covers IPv6 and IP over ATM. Using C on the UNIX System by David A. Curry. Published by O'Reilly & Associates, Inc. ISBN 0-937175-23-4. TCP/IP Network Administration by Craig Hunt. Published by O'Reilly & Associates, Inc. ISBN 0-937175-82-X. TCP/IP Illustrated, volumes 1-3 by W. Richard Stevens and Gary R. Wright. Published by Addison Wesley. ISBNs: 0-201-63346-9, 0-201-63354-X, 0-201-63495-3. Unix Network Programming by W. Richard Stevens. Published by Prentice Hall. ISBN 0-13-949876-1. On the web: BSD Sockets: A Quick And Dirty Primer (http://www.cs.umn.edu/~bentlema/unix/--has other great Unix system programming info, too!) Client-Server Computing (http://pandonia.canberra.edu.au/ClientServer/socket.html) Intro to TCP/IP (gopher)(gopher://gopher-chem.ucdavis.edu/11/Index/Internet_aw/Intro_the_Inter net/intro.to.ip/) Internet Protocol Frequently Asked Questions (France) (http://web.cnam.fr/Network/TCP-IP/) The Unix Socket FAQ (http://www.ibrado.com/sock-faq/) RFCs--the real dirt: RFC-768 -- The User Datagram Protocol (UDP) (ftp://nic.ddn.mil/rfc/rfc768.txt) RFC-791 -- The Internet Protocol (IP) (ftp://nic.ddn.mil/rfc/rfc791.txt) RFC-793 -- The Transmission Control Protocol (TCP) (ftp://nic.ddn.mil/rfc/rfc793.txt) RFC-854 -- The Telnet Protocol (ftp://nic.ddn.mil/rfc/rfc854.txt) RFC-951 -- The Bootstrap Protocol (BOOTP)
(ftp://nic.ddn.mil/rfc/rfc951.txt) RFC-1350 -- The Trivial File Transfer Protocol (TFTP) (ftp://nic.ddn.mil/rfc/rfc1350.txt)