c++ - posix 管道作为消息队列 : What happens on blocked write + signal

标签 c++ linux pipe message-queue atomic

我想使用管道作为内部消息队列,如下所述:posix pipe as a work queue

根据 glibc 的文档,如果数据小于 PIPE_BUF,则写入管道是原子的。 https://www.gnu.org/software/libc/manual/html_node/Pipe-Atomicity.html#Pipe-Atomicity

但是:如果出现信号,写入可能会被中断。假设 write 被阻塞是因为管道快满了。现在出现了一个信号。数据会自动写入管道吗?

template <typename T>
ssize_t put(const T& data)
{       
    static_assert(sizeof(T) < PIPE_BUF, "We use the atomic property of the pipe write. So sizeof(T) MUST be smaller than PIPE_BUF");

    int written;
    const size_t id = T::value;
    written = write(m_fds[write_fd], &id, sizeof(size_t));
    assert(written == sizeof(size_t));

    const size_t sT = sizeof(T);
    write(m_fds[write_fd], &sT, sizeof(size_t));
    assert(written == sizeof(size_t));

    write(m_fds[write_fd], &data, sizeof(T)); // * this blocks in example
    assert(written == sizeof(T));

    return sizeof(T);
}

最佳答案

Atomic 只是意味着 "the whole amount written in one operation is not interleaved with data from any other process."

信号中断略有不同。根据the man page of signal ,管道是一种“慢设备”。因此,除非设置了SA_RESTART,否则write 操作将返回成功并返回写入的数据数。因此,最好经常检查write的返回值,以确保所有数据都已写入。或者,您可以屏蔽可能的信号。

关于c++ - posix 管道作为消息队列 : What happens on blocked write + signal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36173438/

相关文章:

c - 管道数组 : Will parent process load the array fast enough?

c - C中的单向管道

c# - 编写缓存模拟器程序需要注意什么?

linux - 如何将 Linux 引入 WindowsCE 设备

linux - 如何使用 shell 脚本删除 CSV 文件中多行中常见的特定字符串?

linux - 使用带有 vconfig 接口(interface)的 linux 原始套接字

multithreading - Ocaml:有没有办法在进程之间传递对象?

c++ - boost asio串口 "end of file"

c++ - 将引用用作数组/指针是否合法?

c++ - 将模板 typedef 的数组传递给构造函数