1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
/**
* @file stdiodevice.cc
* @brief Implementation of the StdIODevice class
* @author Andreas Aardal Hanssen
* @date 2003/2023
*/
#include "stdiodevice.h"
#include <string>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
using namespace Binc;
StdIODevice::StdIODevice(int f) : IODevice(f) {}
StdIODevice::~StdIODevice(void) {}
std::string StdIODevice::service(void) const
{
return "client";
}
bool StdIODevice::canRead(void) const
{
size_t bytes;
return ioctl(fileno(stdin), FIONREAD, (char *)&bytes) > 0;
}
bool StdIODevice::waitForWrite(void) const
{
fd_set writeMask;
FD_ZERO(&writeMask);
FD_SET(fileno(stdout), &writeMask);
struct timeval tv;
tv.tv_sec = timeout;
tv.tv_usec = 0;
int result = select(fileno(stdout) + 1,
nullptr,
&writeMask,
nullptr,
timeout ? &tv : nullptr);
if (result == 0) error = Timeout;
return result > 0;
}
bool StdIODevice::waitForRead(void) const
{
fd_set readMask;
FD_ZERO(&readMask);
FD_SET(fileno(stdin), &readMask);
struct timeval tv;
tv.tv_sec = timeout;
tv.tv_usec = 0;
int result = select(fileno(stdin) + 1, &readMask, nullptr, nullptr, timeout ? &tv : nullptr);
if (result == 0) error = Timeout;
return result > 0;
}
IODevice::WriteResult StdIODevice::write(void)
{
for (;;) {
ssize_t wrote = ::write(fileno(stdout),
outputBuffer.str().c_str(),
outputBuffer.getSize());
if (wrote == -1) {
if (errno == EINTR)
continue;
else
return WriteError;
}
outputBuffer.popString(wrote);
if (wrote == (ssize_t)outputBuffer.getSize()) return WriteDone;
return WriteWait;
}
}
bool StdIODevice::fillInputBuffer(void)
{
if (!waitForRead()) return false;
char buf[4096];
ssize_t red = read(fileno(stdin), buf, sizeof(buf) - 1);
if (red <= 0) return false;
buf[red] = '\0';
inputBuffer << buf;
return true;
}
|