28 #include "fatal-error.h"
29 #include "simple-ref-count.h"
30 #include "system-thread.h"
31 #include "simulator.h"
33 #include "unix-fd-reader.h"
40 : m_fd (-1), m_readCallback (0), m_readThread (0), m_stop (false),
48 FdReader::~FdReader ()
59 NS_ASSERT_MSG (m_readThread == 0,
"read thread already exists");
62 tmp = pipe (m_evpipe);
69 tmp = fcntl (m_evpipe[0], F_GETFL);
74 if (fcntl (m_evpipe[0], F_SETFL, tmp | O_NONBLOCK) == -1)
80 m_readCallback = readCallback;
102 m_readThread = Create<SystemThread> (
MakeCallback (&FdReader::Run,
this));
103 m_readThread->Start ();
106 void FdReader::DestroyEvent (
void)
119 if (m_evpipe[1] != -1)
122 ssize_t len = write (m_evpipe[1], &zero,
sizeof (zero));
123 if (len !=
sizeof (zero))
124 NS_LOG_WARN (
"incomplete write(): " << std::strerror (errno));
128 if (m_readThread != 0)
130 m_readThread->Join ();
135 if (m_evpipe[1] != -1)
142 if (m_evpipe[0] != -1)
150 m_readCallback.Nullify ();
155 void FdReader::Run (
void)
161 nfds = (
m_fd > m_evpipe[0] ?
m_fd : m_evpipe[0]) + 1;
164 FD_SET (
m_fd, &rfds);
165 FD_SET (m_evpipe[0], &rfds);
170 fd_set readfds = rfds;
172 r = select (nfds, &readfds, NULL, NULL, NULL);
173 if (r == -1 && errno != EINTR)
178 if (FD_ISSET (m_evpipe[0], &readfds))
184 ssize_t len = read (m_evpipe[0], buf,
sizeof (buf));
191 if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
209 if (FD_ISSET (
m_fd, &readfds))
211 struct FdReader::Data data =
DoRead ();
219 else if (data.m_len > 0)
221 m_readCallback (data.m_buf, data.m_len);
void Start(int fd, Callback< void, uint8_t *, ssize_t > readCallback)
#define NS_LOG_FUNCTION(parameters)
#define NS_LOG_COMPONENT_DEFINE(name)
bool IsRunning(void) const
#define NS_FATAL_ERROR(msg)
fatal error handling
int m_fd
The file descriptor to read from.
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
#define NS_LOG_LOGIC(msg)
#define NS_ASSERT_MSG(condition, message)
virtual FdReader::Data DoRead(void)=0
The read implementation.
static EventId ScheduleDestroy(MEM mem_ptr, OBJ obj)