1 // Copyright (c) 2011-2015 Ryan Prichard
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to
5 // deal in the Software without restriction, including without limitation the
6 // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 // sell copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 #include "InputHandler.h"
26 #include <sys/select.h>
32 #include "../shared/DebugClient.h"
36 InputHandler::InputHandler(
37 HANDLE conin, int inputfd, WakeupFd &completionWakeup) :
40 m_completionWakeup(completionWakeup),
41 m_threadHasBeenJoined(false),
45 pthread_create(&m_thread, NULL, InputHandler::threadProcS, this);
48 void InputHandler::shutdown() {
50 if (!m_threadHasBeenJoined) {
51 int ret = pthread_join(m_thread, NULL);
52 assert(ret == 0 && "pthread_join failed");
53 m_threadHasBeenJoined = true;
57 void InputHandler::threadProc() {
58 std::vector<char> buffer(4096);
64 if (m_shouldShutdown) {
65 trace("InputHandler: shutting down");
69 // Block until data arrives.
71 const int max_fd = std::max(m_inputfd, m_wakeup.fd());
72 FD_SET(m_inputfd, &readfds);
73 FD_SET(m_wakeup.fd(), &readfds);
74 selectWrapper("InputHandler", max_fd + 1, &readfds);
75 if (!FD_ISSET(m_inputfd, &readfds)) {
80 const int numRead = read(m_inputfd, &buffer[0], buffer.size());
81 if (numRead == -1 && errno == EINTR) {
82 // Apparently, this read is interrupted on Cygwin 1.7 by a SIGWINCH
83 // signal even though I set the SA_RESTART flag on the handler.
87 // tty is closed, or the read failed for some unexpected reason.
89 trace("InputHandler: tty read failed: numRead=%d", numRead);
94 BOOL ret = WriteFile(m_conin,
97 if (!ret || written != static_cast<DWORD>(numRead)) {
98 if (!ret && GetLastError() == ERROR_BROKEN_PIPE) {
99 trace("InputHandler: pipe closed: written=%u",
100 static_cast<unsigned int>(written));
102 trace("InputHandler: write failed: "
103 "ret=%d lastError=0x%x numRead=%d written=%u",
105 static_cast<unsigned int>(GetLastError()),
107 static_cast<unsigned int>(written));
112 m_threadCompleted = 1;
113 m_completionWakeup.set();