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