SIGPIPE信号的产生以及处理

来源:互联网 发布:蜜蜂软件官方下载 编辑:程序博客网 时间:2024/06/05 19:00

看了TCP的一些东西,知道服务器往以及关闭了的sockfd中写两次时,会产生SIGPIPE信号,如果不处理,默认会挂掉服务器

弄个小例子测试一下:

#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;}

客户端使用telnet连接

发现:

   当客户端关闭后,服务器端还会写两次后,就会收到SIGPIPE信号,后续继续会收到此信号

telnet localhost 8888

--》客户端:

  

syswj@host ~]$ telnet localhost 8888Trying ::1...telnet: connect to address ::1: Connection refusedTrying 127.0.0.1...Connected to localhost.Escape character is '^]'.hellohellohello^]telnet> Connection closed.

   服务器信息:

  

➜  mianshi git:(master) ✗ ./a.out clienthellohellohellohello   //-》对方会发送一个RST复位报文hellosigpipe   hellosigpipe    //-->是由于write导致的hellosigpipehellosigpipe^C

可以看到是在客户端关闭后,再发送 第2个信息后才收到的SIFPIPE信号

后续发送仍然会收到SIGPIPE信号

       




0 0
原创粉丝点击