using istream to read from named pipe

2020-07-18 06:06发布

Is it possible to read from named pipe (mkfifo) using c++ (stl) using a stream - thus not defining in advance char *buffer[MAX_SIZE] for the read operation?

I want to read till the buffer ends and put the result into std::string.

(Current method: bytes = read(fd, buffer, sizeof(buffer)); requires allocation some kind of buffer in advance.)

2条回答
我命由我不由天
2楼-- · 2020-07-18 06:23

There's nothing magical about piping to your program it just turns your cin reading from the stream instead of the user's input from the console: Linux terminal pipe to my C++ program

A simple glance at this question's edit history will show that this question has greatly improved from it's original version thanks to Konrad Rudolph (the other answerer on this question.) In a move of further dastardliness I'm going to scrape 2 of his solutions for slurping a stream into string:

istreambuf_iterator method:

const string mkfifo{ istreambuf_iterator<char>(cin), istreambuf_iterator<char>() };

stringbuf copy method:

istringstream temp;
temp << cin.rdbuf();
const auto mkfifo = temp.str();

You can read about the pros and cons of each on their respective posts. To use this code, say that your compiled program is named main you would pipe to it like this:

mkfifo named_pipe
echo "lorem ipsum" > named_pipe
./main named_pipe
查看更多
我想做一个坏孩纸
3楼-- · 2020-07-18 06:28

Named pipes created with mkfifo behave like regular files. Thus they can be accessed using std::ifstream and std::ofstream:

#include <fstream>
#include <iostream>

int main(int, char** argv) {
    std::ifstream file{argv[1]};
    std::string line;
    std::getline(file, line);
    std::cout << line << '\n';
}

Run:

mkfifo foobar
./main foobar

And elsewhere:

echo 'Hello world!' > foobar

… this will cause ./main to print “Hello world!” to the standard output.

查看更多
登录 后发表回答