mirror of
https://github.com/audacity/linuxdeploy.git
synced 2026-04-18 20:11:56 -05:00
Add new helper class pipe reader
Implements synchronous, non-block reading from pipes.
This commit is contained in:
36
include/linuxdeploy/subprocess/pipe_reader.h
Normal file
36
include/linuxdeploy/subprocess/pipe_reader.h
Normal file
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
#include <poll.h>
|
||||
|
||||
/**
|
||||
* Reads from a pipe when data is available, and hands data to registered callbacks.
|
||||
*/
|
||||
class pipe_reader {
|
||||
private:
|
||||
const int pipe_fd_;
|
||||
|
||||
public:
|
||||
/**
|
||||
* Construct new instance from pipe file descriptor.
|
||||
* @param pipe_fd file descriptor for pipe we will read from (e.g., a subprocess's stdout, stderr pipes)
|
||||
*/
|
||||
explicit pipe_reader(int pipe_fd);
|
||||
|
||||
/**
|
||||
* Read from pipe file descriptor and store data in buffer.
|
||||
* This method is non-blocking, i.e., if there is no data to read, it returns immediately.
|
||||
* Otherwise, it will read until either of the following conditions is met:
|
||||
*
|
||||
* - no more data left in the pipe to be read
|
||||
* - buffer is completely filled
|
||||
*
|
||||
* On errors, a subprocess_error is thrown.
|
||||
*
|
||||
* @param buffer buffer to store read data into
|
||||
* @returns amount of characters read from the pipe
|
||||
*/
|
||||
size_t read(std::vector<std::string::value_type>& buffer) const;
|
||||
};
|
||||
31
src/subprocess/pipe_reader.cpp
Normal file
31
src/subprocess/pipe_reader.cpp
Normal file
@@ -0,0 +1,31 @@
|
||||
// system headers
|
||||
#include <algorithm>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <functional>
|
||||
#include <cstring>
|
||||
|
||||
// local headers
|
||||
#include "linuxdeploy/subprocess/pipe_reader.h"
|
||||
|
||||
pipe_reader::pipe_reader(int pipe_fd) : pipe_fd_(pipe_fd) {
|
||||
// add O_NONBLOCK TO fd's flags to be able to read
|
||||
auto flags = fcntl(pipe_fd_, F_GETFL, 0);
|
||||
flags |= O_NONBLOCK;
|
||||
fcntl(pipe_fd_, F_SETFL, flags);
|
||||
}
|
||||
|
||||
size_t pipe_reader::read(std::vector<std::string::value_type>& buffer) const {
|
||||
ssize_t rv = ::read(pipe_fd_, buffer.data(), buffer.size());
|
||||
|
||||
if (rv == -1) {
|
||||
// no data available
|
||||
if (errno == EAGAIN)
|
||||
return 0;
|
||||
|
||||
// TODO: introduce custom subprocess_error
|
||||
throw std::runtime_error{"unexpected error reading from pipe: " + std::string(strerror(errno))};
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
Reference in New Issue
Block a user