Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion of improvement for pipes on windows #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions include/nes/pipe.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
#include <memory>
#include <cassert>
#include <utility>
#include <thread>
#include <chrono>

#if defined(NES_WIN32_PIPE)

Expand Down Expand Up @@ -138,15 +140,31 @@ class basic_pipe_streambuf : public std::basic_streambuf<CharT, Traits>
{
native_mode = mode & std::ios_base::in ? PIPE_ACCESS_INBOUND : PIPE_ACCESS_OUTBOUND;

handle = CreateNamedPipeW(std::data(native_name), native_mode, PIPE_READMODE_BYTE | PIPE_WAIT, 1, buf_size, buf_size, 0, nullptr);
// use NOWAIT mode so that ConnectNamedPipe won't block forever
handle = CreateNamedPipeW(std::data(native_name), native_mode, PIPE_READMODE_BYTE | PIPE_NOWAIT, 1, buf_size, buf_size, 0, nullptr);
if(handle == INVALID_HANDLE_VALUE)
return false;

if(!ConnectNamedPipe(handle, nullptr))
OVERLAPPED overlap{};
BOOL ok = ConnectNamedPipe(handle, &overlap);
if(ok && GetLastError() == ERROR_IO_PENDING) // IO_PENDING is the state we want to be in
{
if (!HasOverlappedIoCompleted(&overlap)) // that macro can only be called when in PENDING state
{
// wait but don't block for too long so that the calling thread remains salvageable
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // default internal windows timeouts are 80ms
ok = HasOverlappedIoCompleted(&overlap);
}
}

if (!ok)
{
CancelIo(handle);
CloseHandle(handle);
return false;
}
// switch back to synchronous IO after connection is established
SetNamedPipeHandleState(handle, PIPE_READMODE_BYTE | PIPE_WAIT, NULL, NULL);
}
}

Expand Down