3.SIGPIPE问题
人怕牺牲,我们写的程序也一样,人有死不瞑目,程序又何尝不是?程序跑着跑着,突然就崩掉了。好一点的牺牲前告诉你些打印,差点的也能用core文件等一些手段查出死在哪了,最惨不忍睹的就是程序没了,core也没了,这真是死得莫名其妙。我们在写socket程序时,也会有这种困扰。
下面我又要开始极尽构造之能事了,客户端代码如下:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <string.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <netdb.h> 9 10 #define PORT 1234 11 #define MAXDATASIZE 1000 12 13 int main(int argc, char *argv[]) 14 { 15 int sockfd, num; 16 char szbuf[MAXDATASIZE] = {0}; 17 struct sockaddr_in server; 18 19 if (argc != 2) 20 { 21 printf("Usage:%s <IP Address> ", argv[0]); 22 exit(1); 23 } 24 25 if ((sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1) 26 { 27 printf("socket()error "); 28 exit(1); 29 } 30 bzero(&server, sizeof(server)); 31 server.sin_family = AF_INET; 32 server.sin_port = htons(PORT); 33 server.sin_addr.s_addr = inet_addr(argv[1]); 34 if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1) 35 { 36 printf("connect()error "); 37 exit(1); 38 } 39 40 memset(szbuf, 'a', sizeof(szbuf)); 41 while (1) 42 { 43 printf("a send "); 44 send(sockfd, szbuf, sizeof(szbuf), 0); 45 sleep(10); 46 } 47 48 close(sockfd); 49 50 return 0; 51 }
然后是服务器代码:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <unistd.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <arpa/inet.h> 9 10 #define PORT 1234 11 #define BACKLOG 5 12 #define MAXDATASIZE 1000 13 14 int main() 15 { 16 int listenfd, connectfd; 17 struct sockaddr_in server; 18 struct sockaddr_in client; 19 socklen_t addrlen; 20 char szbuf[MAXDATASIZE + 1] = {0}; 21 int num = 0; 22 23 if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 24 { 25 perror("Creating socket failed."); 26 exit(1); 27 } 28 29 int opt = SO_REUSEADDR; 30 setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); 31 32 bzero(&server, sizeof(server)); 33 server.sin_family = AF_INET; 34 server.sin_port = htons(PORT); 35 server.sin_addr.s_addr = htonl(INADDR_ANY); 36 if (bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1) 37 { 38 perror("Bind()error."); 39 exit(1); 40 } 41 if (listen(listenfd, BACKLOG) == -1) 42 { 43 perror("listen()error "); 44 exit(1); 45 } 46 47 addrlen = sizeof(client); 48 if ((connectfd = accept(listenfd, (struct sockaddr*)&client, &addrlen)) == -1) 49 { 50 perror("accept()error "); 51 exit(1); 52 } 53 printf("You got a connection from cient's ip is %s, prot is %d ", inet_ntoa(client.sin_addr), htons(client.sin_port)); 54 55 while (1) 56 { 57 memset(szbuf, 0, sizeof(szbuf)); 58 if ((num = recv(connectfd, szbuf, MAXDATASIZE,0)) == -1) 59 { 60 printf("recv() error "); 61 exit(1); 62 } 63 szbuf[num - 1] = '