1. 程式人生 > >解決Linux下網路程式設計(sendto send )出現 SIGPIPE 訊號導致程式異常終止的問題

解決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)來進行後續操作。