#include #include #include #include #include #include #include #include #include void error(const char *str) { perror(str); exit(1); } void worker(int listenfd) { int fd; struct sockaddr_in peeraddr; socklen_t len = sizeof(peeraddr); int pid; char buf[100]; while(1) { memset(&peeraddr, 0, sizeof(peeraddr)); fd = accept(listenfd, (struct sockaddr *)&peeraddr, &len); if (fd < 0) error("accept"); pid = fork(); if (pid < 0) { error("fork"); } else if (pid != 0) { close(fd); /* while(1) sleep(1); */ } else { read(fd, &buf, sizeof(buf)); while(1) sleep(1); exit(0); } } exit(0); } int main(int argc, char **argv) { int listenfd; struct sockaddr_in myaddr; int res; pid_t pid; int i; if (argc < 3) { fprintf(stderr, "%s serverport processes\n", argv[0]); exit(1); } listenfd = socket(PF_INET, SOCK_STREAM, 0); if (listenfd < 0) error("socket"); memset(&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = PF_INET; myaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); myaddr.sin_port = htons(atoi(argv[1])); res = bind(listenfd, (struct sockaddr *)&myaddr, sizeof(myaddr)); if (res < 0) error("bind"); /* distccd uses 10 here */ if (listen(listenfd, 10) < 0) error("listen"); for (i = 0; i < atoi(argv[2]); i++) { pid = fork(); if (pid < 0) error("fork"); if (pid == 0) { worker(listenfd); } } while (1) { sleep(1); } return 0; }