4、例子重用 The Bazaar原则二: Good programmers know what to write. Great ones know what to rewrite (and reuse). 好的程序员知道写什么。而伟大的程序员知道重写和重用什么。 基于这个原则,我当然不会从头来写这个程序(其实,这个程序是一个很小的程序,没有必要一定要这么做。 但是,为了给大家,同时也是给我自己一个集市化的开发方式的体验,我还是这么做了,我先是写出来了一个 简单的程序---附在本文最后----然后才想起来去找找有没有类似的程序 :-), 结果浪费了很多时间)。 在网上找了找,花了大概半个小时( 和我写出第一个简单程序所花的时间差不多 :-) ),找到了这个程序。 程序如下: ------------------------------------------------------------------------------------------------ /**************************************************************************** program: proxyd module: proxyd.c summary: provides proxy tcp service for a host on an isolated network.
programmer: Carl Harris (ceharris@vt.edu) date: 22 Feb 94
description: This code implements a daemon process which listens for tcp connec- tions on a specified port number. When a connection is established, a child is forked to handle the new client. The child then estab- lishes a tcp connection to a port on the isolated host. The child then falls into a loop in which it writes data to the isolated host for the client and vice-versa. Once a child has been forked, the parent resumes listening for additional connections.
The name of the isolated host and the port to serve as proxy for, as well as the port number the server listen on are specified as command line arguments. ****************************************************************************/
function: main description: Main level driver. After daemonizing the process, a socket is opened to listen for connections on the proxy port, connections are accepted and children are spawned to handle each new connection. arguments: argc,argv you know what those are.
main (argc,argv) int argc; char **argv; { int clilen; int childpid; int sockfd, newsockfd; struct sockaddr_in servaddr, cliaddr;
parse_args(argc,argv);
/* prepare an address struct to listen for connections */ bzero((char *) &servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = proxy_port;
/* get a socket... */ if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0) { fputs("failed to create server socket ",stderr); exit(1); }
/* ...and bind our address and port to it */ if (bind(sockfd,(struct sockaddr_in *) &servaddr,sizeof(servaddr)) < 0) { fputs("faild to bind server socket to specified port ",stderr); exit(1); }
/* get ready to accept with at most 5 clients waiting to connect */ listen(sockfd,5);
/* turn ourselves into a daemon */ daemonize(sockfd);
/* fall into a loop to accept new connections and spawn children */ while (1) {
/* accept the next connection */ clilen = sizeof(cliaddr); newsockfd = accept(sockfd, (struct sockaddr_in *) &cliaddr, &clilen); if (newsockfd < 0 && errno == EINTR) continue; /* a signal might interrupt our accept() call */ else if (newsockfd < 0) /* something quite amiss -- k