system/FileDescriptor: add pipe2() wrapper

This commit is contained in:
Max Kellermann 2018-08-20 17:02:34 +02:00
parent 795baed3f5
commit 8106929d60
2 changed files with 31 additions and 18 deletions

View File

@ -115,15 +115,33 @@ FileDescriptor::OpenNonBlocking(const char *pathname) noexcept
#endif #endif
#ifdef __linux__
bool
FileDescriptor::CreatePipe(FileDescriptor &r, FileDescriptor &w,
int flags) noexcept
{
int fds[2];
const int result = pipe2(fds, flags);
if (result < 0)
return false;
r = FileDescriptor(fds[0]);
w = FileDescriptor(fds[1]);
return true;
}
#endif
bool bool
FileDescriptor::CreatePipe(FileDescriptor &r, FileDescriptor &w) noexcept FileDescriptor::CreatePipe(FileDescriptor &r, FileDescriptor &w) noexcept
{ {
#ifdef __linux__
return CreatePipe(r, w, O_CLOEXEC);
#else
int fds[2]; int fds[2];
#ifdef __linux__ #ifdef _WIN32
const int flags = O_CLOEXEC;
const int result = pipe2(fds, flags);
#elif defined(_WIN32)
const int result = _pipe(fds, 512, _O_BINARY); const int result = _pipe(fds, 512, _O_BINARY);
#else #else
const int result = pipe(fds); const int result = pipe(fds);
@ -135,6 +153,7 @@ FileDescriptor::CreatePipe(FileDescriptor &r, FileDescriptor &w) noexcept
r = FileDescriptor(fds[0]); r = FileDescriptor(fds[0]);
w = FileDescriptor(fds[1]); w = FileDescriptor(fds[1]);
return true; return true;
#endif
} }
#ifndef _WIN32 #ifndef _WIN32
@ -143,27 +162,16 @@ bool
FileDescriptor::CreatePipeNonBlock(FileDescriptor &r, FileDescriptor::CreatePipeNonBlock(FileDescriptor &r,
FileDescriptor &w) noexcept FileDescriptor &w) noexcept
{ {
int fds[2];
#ifdef __linux__ #ifdef __linux__
const int flags = O_CLOEXEC|O_NONBLOCK; return CreatePipe(r, w, O_CLOEXEC|O_NONBLOCK);
const int result = pipe2(fds, flags);
#else #else
const int result = pipe(fds); if (!CreatePipe(r, w))
#endif
if (result < 0)
return false; return false;
r = FileDescriptor(fds[0]);
w = FileDescriptor(fds[1]);
#ifndef __linux__
r.SetNonBlocking(); r.SetNonBlocking();
w.SetNonBlocking(); w.SetNonBlocking();
#endif
return true; return true;
#endif
} }
void void

View File

@ -129,6 +129,11 @@ public:
bool OpenNonBlocking(const char *pathname) noexcept; bool OpenNonBlocking(const char *pathname) noexcept;
#endif #endif
#ifdef __linux__
static bool CreatePipe(FileDescriptor &r, FileDescriptor &w,
int flags) noexcept;
#endif
static bool CreatePipe(FileDescriptor &r, FileDescriptor &w) noexcept; static bool CreatePipe(FileDescriptor &r, FileDescriptor &w) noexcept;
#ifdef _WIN32 #ifdef _WIN32