SIGPIPE并产生一个信号处理
阅读TCP某物,知道server并关闭sockfd当写两次,会产生SIGPIPE信号,假如不治疗,默认将挂起server
弄个小样本试验:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <signal.h>
#define ERR_EXIT(m) \
do { \
perror(m);\
exit(EXIT_FAILURE);\
}while(0)
void handle(int arg)
{
printf("sigpipe\n");
}
int main(int argc, const char *argv[])
{
signal(SIGPIPE, handle);//SIGPIPE信号的处理
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
ERR_EXIT("socket");
struct sockaddr_in seraddr;
seraddr.sin_family = AF_INET;
seraddr.sin_port = htons(8888);
seraddr.sin_addr.s_addr = inet_addr("127.0.0.1") ;
socklen_t len = sizeof(seraddr);
if(-1 == (bind(sockfd, (struct sockaddr*)&seraddr, len)))
ERR_EXIT("bind");
if(listen(sockfd, 3) == -1)
ERR_EXIT("listen");
int clientfd = accept(sockfd, NULL, NULL);
printf("client\n");
while(1)
{
sleep(3);
printf("hello\n");
write(clientfd, "hello", sizeof("hello"));
}
return 0;
}
client使用telnet连接
发现:
当client关闭后,server端还会写两次后。就会收到SIGPIPE信号,兴许继续会收到此信号
telnet localhost 8888
--》client:
syswj@host ~]$ telnet localhost 8888 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hello hello hello ^] telnet> Connection closed.
server信息:
➜ mianshi git:(master) ✗ ./a.out client hello hello hello hello //-》对方会发送一个RST复位报文 hello sigpipe hello sigpipe //-->是因为write导致的 hello sigpipe hello sigpipe ^C
能够看到是在client关闭后,再发送 第2个信息后才收到的SIFPIPE信号
兴许发送仍然会收到SIGPIPE信号
版权声明:本文博客原创文章。博客,未经同意,不得转载。
浙公网安备 33010602011771号