TCP测试用客户程序
1 #include "unp.h" 2 3 #define MAXN 16384 /* max # bytes to request from server */ 4 5 int 6 main(int argc, char **argv) 7 { 8 int i, j, fd, nchildren, nloops, nbytes; 9 pid_t pid; 10 ssize_t n; 11 char request[MAXLINE], reply[MAXN]; 12 13 if (argc != 6) 14 err_quit("usage: client <hostname or IPaddr> <port> <#children> " 15 "<#loops/child> <#bytes/request>"); 16 17 nchildren = atoi(argv[3]); 18 nloops = atoi(argv[4]); 19 nbytes = atoi(argv[5]); 20 snprintf(request, sizeof(request), "%d\n", nbytes); /* newline at end */ 21 22 for (i = 0; i < nchildren; i++) { 23 if ( (pid = Fork()) == 0) { /* child */ 24 for (j = 0; j < nloops; j++) { 25 fd = Tcp_connect(argv[1], argv[2]); 26 27 Write(fd, request, strlen(request)); 28 29 if ( (n = Readn(fd, reply, nbytes)) != nbytes) 30 err_quit("server returned %d bytes", n); 31 32 Close(fd); /* TIME_WAIT on client, not server */ 33 } 34 printf("child %d done\n", i); 35 exit(0); 36 } 37 /* parent loops around to fork() again */ 38 } 39 40 while (wait(NULL) > 0) /* now parent waits for all children */ 41 ; 42 if (errno != ECHILD) 43 err_sys("wait error"); 44 45 exit(0); 46 }