2025年linux sigpipe信号,Linux下SIGPIPE信号及其处理「建议收藏」

linux sigpipe信号,Linux下SIGPIPE信号及其处理「建议收藏」在 Linux 下写 socket 的程序的时候 如果尝试 send 到一个 disconnected socket 上 就会让底层抛出一个 SIGPIPE 信号 这个信号的缺省处理方法是退出进程 大多数时候这都不是我们期望的 因此我们需要重载这个信号的处理方法 调用以下代码 即可安全的屏蔽 SIGPIPE struct sigaction sa sa sa handler SIG IGN

在Linux下写socket的程序的时候,如果尝试send到一个disconnected socket上,就会让底层抛出一个SIGPIPE信号。

这个信号的缺省处理方法是退出进程,大多数时候这都不是我们期望的。因此我们需要重载这个信号的处理方法。

调用以下代码,即可安全的屏蔽SIGPIPE:

struct sigaction sa;

sa.sa_handler = SIG_IGN;

sigaction( SIGPIPE, &sa, 0 );

//======================================================================

SIGPIPE

From Wikipedia, the free encyclopedia

Jump to: navigation, searchSIGPIPE Description Write on a pipe with no one to read it

Default action Abnormal termination of the process

SA_SIGINFOmacros

one

On POSIX-compliant platforms, SIGPIPE is the signal raised when a computer program attempts to write to a pipe without a process connected to the other end. The symbolic constant for SIGPIPE is defined in the header file signal.h. Symbolic signal names are used because signal numbers can vary across platforms.

Etymology

SIG is a common prefix for signal names. PIPE refers to the Unix pipe.

Description

Unix supports the principle of piping, which allows processes to send data to other processes without the need for creating temporary files. When a pipe is broken, the process writing to it is sent the SIGPIPE signal. The default reaction to this signal for a process is to terminate.

A simple example of piping is the following.

ps l | head

This command, when run on a Unix-like machine (including Linux), returns a list of processes, limited to ten lines.

ps l returns a list of all processes (including those of other users).

head selects the first ten lines.

When ps has written ten lines, head has received all it needs and exits. ps will receive a SIGPIPE when it tries to write the remaining lines, causing it to terminate as well: It is no use writing data that no one will use. It is also possible that the reading process terminates while reading the data. This will also cause SIGPIPE to be sent to the writing process.

One can ignore SIGPIPE (using, for example, the signal system call). In this case, all system calls that would cause SIGPIPE to be sent will return -1 and set errno to EPIPE.

编程小号
上一篇 2025-02-26 07:40
下一篇 2025-03-14 21:46

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/hz/124155.html