解决Linux下网络编程(sendto send )出现 SIGPIPE 信号导致程序异常终止的问题

引言

最近在Linux下网络编程时,出现SIGPIPE 信号导致程序异常终止,本文记录下解决的方法以及相应的知识。

SIGPIPE 信号资料

什么时候出现此信号,APUE中有关此信号的解释如下:
SIGPIPE
Linux man手册有关此信号的解释:

man 7 signal 
SIGPIPE      13       Term    Broken pipe: write to pipe with no readers

现在基本上可以推断出是对方socket关闭导致,这边sendto失败。

解决方案

想办法屏蔽掉此信号,尤其是网络编程中,在Linux下man手册同样提供了解决方案

man sendto 

通过设置send的标志来解决此问题

MSG_NOSIGNAL (since Linux 2.2)
              Don't generate a SIGPIPE signal if the peer on a stream-oriented socket has closed     the  connection.   The  EPIPE
              error  is  still  returned.  This provides similar behavior to using sigaction(2) to ignore SIGPIPE, but, whereas
              MSG_NOSIGNAL is a per-call feature, ignoring SIGPIPE sets a process attribute that affects  all  threads  in  the
              process.

通过这种方法来忽略此信号,并且对返回值进行判断,根据errno(EPIPE)来进行后续操作。

猜你喜欢

转载自blog.csdn.net/wanxuexiang/article/details/84027325