diff options
author | 2016-11-18 11:19:02 +0000 | |
---|---|---|
committer | 2016-11-18 13:20:16 +0000 | |
commit | ef5ceef023ee630f7efb4c406be3937713b19b6b (patch) | |
tree | aeaec34329f276cdb21e2c9d047d2c0c68d326ed /src/main/cpp/util/file_posix.cc | |
parent | 84a3ed95143a14d05d9459b555fd09ad645aa707 (diff) |
Bazel client: create a wrapper around Unix pipes
This allows implementing pipe-handling in a
platform-specific way. Windows also supports pipes
but through its own API.
--
MOS_MIGRATED_REVID=139564316
Diffstat (limited to 'src/main/cpp/util/file_posix.cc')
-rw-r--r-- | src/main/cpp/util/file_posix.cc | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/main/cpp/util/file_posix.cc b/src/main/cpp/util/file_posix.cc index b6c37e19cc..5bb8772d70 100644 --- a/src/main/cpp/util/file_posix.cc +++ b/src/main/cpp/util/file_posix.cc @@ -33,6 +33,53 @@ namespace blaze_util { using std::pair; using std::string; +class PosixPipe : public IPipe { + public: + PosixPipe(int recv_socket, int send_socket) + : _recv_socket(recv_socket), _send_socket(send_socket) {} + + PosixPipe() = delete; + + virtual ~PosixPipe() { + close(_recv_socket); + close(_send_socket); + } + + // Sends `size` bytes from `buffer` through the pipe. + bool Send(void* buffer, size_t size) override { + return write(_send_socket, buffer, size) == size; + } + + // Receives at most `size` bytes into `buffer` from the pipe. + // Returns the number of bytes received; sets `errno` upon error. + int Receive(void* buffer, size_t size) override { + return read(_recv_socket, buffer, size); + } + + private: + int _recv_socket; + int _send_socket; +}; + +IPipe* CreatePipe() { + int fd[2]; + if (pipe(fd) < 0) { + pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, "pipe()"); + } + + if (fcntl(fd[0], F_SETFD, FD_CLOEXEC) == -1) { + pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, + "fcntl(F_SETFD, FD_CLOEXEC) failed"); + } + + if (fcntl(fd[1], F_SETFD, FD_CLOEXEC) == -1) { + pdie(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR, + "fcntl(F_SETFD, FD_CLOEXEC) failed"); + } + + return new PosixPipe(fd[0], fd[1]); +} + string Which(const string &executable) { char *path_cstr = getenv("PATH"); if (path_cstr == NULL || path_cstr[0] == '\0') { |