Unix pipes

A pipe is a mechanism for sending information from one process to another. In its simplest form, a pipe is a file (in RAM) that one process can write to, and the other can read from. The file starts out empty, and no bytes can be read from the pipe until bytes are written to it.

Let's look at the following example:

#include <string.h>#include <unistd.h>#include <sys/wait.h>#include <array>#include <iostream>#include <string_view>class mypipe{    std::array<int, 2> m_handles;public:    mypipe()    {        if (pipe(m_handles.data()) < 0) {            exit(1);        }    }    ~mypipe()    {        close(m_handles.at(0));        close(m_handles.at(1));    }    std::string    read()    {        std::array<char, 256> buf;        std::size_t bytes = ::read(m_handles.at(0), buf.data(), buf.size()); if (bytes > 0) ...

Get Hands-On System Programming with C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.