- 1#include 2#include < string.h > 3#include 4#include 5#include 6 7#define IP "127.0.0.1"8#define PORT 8888 9#define WORKER 4 10#define MAXIN 4096 11#define MAXLINE 4096 12 13 int tcp_connect(const char * host, const char * port) 14 {
- 15
- if (host == NULL || port == NULL) {
- 16
- return - 1;
- 17
- }
- 18 int sockfd,
- n;
- 19 struct addrinfo hints,
- *res,
- *ressave;
- 20 bzero( & hints, sizeof(struct addrinfo));
- 21 hints.ai_family = AF_UNSPEC;
- 22 hints.ai_socktype = SOCK_STREAM;
- 23
- if ((n = getaddrinfo(host, port, &hints, &res)) != 0) {
- 24 printf("tcp_connect error for %s,%s: %s\n", host, port, strerror(errno));
- 25
- return - 1;
- 26
- }
- 27 ressave = res;
- 28 do {
- 29 sockfd = socket(res - >ai_family, res - >ai_socktype, res - >ai_protocol);
- 30
- if (sockfd < 0) {
- 31
- continue;
- 32
- }
- 33
- if (connect(sockfd, res - >ai_addr, res - >ai_addrlen) == 0) {
- 34
- break;
- 35
- }
- 36 close(sockfd);
- 37
- } while (( res = res - > ai_next ) != NULL);
- 38
- if (res == NULL) {
- 39 printf("tcp_connect error for %s,%s: %s", host, port, strerror(errno));
- 40
- return - 1;
- 41
- }
- 42 freeaddrinfo(ressave);
- 43
- return sockfd;
- 44
- }
- 45 46 int main(int argc, char * *argv) 47 {
- 48
- if (argc != 6) {
- 49 printf("usage: client <hostname or IPaddr> <port> <#children> <#loops/child> <#bytes/request>\n");
- 50
- return - 1;
- 51
- }
- 52 53 int i,
- j,
- fd,
- nchildlen,
- nloops,
- nbytes;
- 54 pid_t pid;
- 55 ssize_t n;
- 56 char request[MAXLINE],
- reply[MAXIN];
- 57 nchildlen = atoi(argv[3]);
- 58 nloops = atoi(argv[4]);
- 59 nbytes = atoi(argv[5]);
- 60 snprintf(request, sizeof(request), "%d\n", nbytes);
- 61
- for (i = 0; i < nchildlen; i++) {
- 62
- if ((pid = fork()) == 0) {
- 63
- for (j = 0; j < nloops; j++) {
- 64 fd = tcp_connect(argv[1], argv[2]);
- 65
- if (fd > 0) {
- 66 write(fd, request, strlen(request));
- 67 68
- if ((n = read(fd, reply, nbytes)) != nbytes) {
- 69 printf("read from server is:%s\n", reply);
- 70
- }
- 71 close(fd);
- 72
- } else {
- 73
- break;
- 74
- }
- 75
- }
- 76 printf("child %d done\n", i);
- 77 exit(0);
- 78
- }
- 79
- }
- 80
- /*waits all child process*/
- 81
- while (wait(NULL) > 0) 82;
- 83
- if (errno != ECHILD) {
- 84 fprintf(stderr, "wait error");
- 85
- return - 1;
- 86
- }
- 87
- return 0;
- 88
- }
来源: http://www.cnblogs.com/Anker/p/7075141.html