-
Notifications
You must be signed in to change notification settings - Fork 0
/
STDIORedirectNative.cpp
60 lines (51 loc) · 1.22 KB
/
STDIORedirectNative.cpp
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
#include "STDIORedirectNative.h"
#include <stdio.h>
#include <unistd.h>
#include <stdexcept>
#include <iostream>
#include <fstream>
using namespace std;
STDIORedirectNative::STDIORedirectNative(int fileno)
{
if((fileno != 1) && (fileno != 2))
throw std::runtime_error("Can only redirect stdout or stderr!");
if (-1 == pipe(_filedes))
throw std::runtime_error("pipe failed");
if (-1 == dup2(_filedes[1], fileno))
{
close();
throw std::runtime_error("dup2 failed");
}
// set proper buffering
if(1 == fileno)
setvbuf(stdout, NULL, _IOLBF, 0); // stdout should be line buffered
else
setvbuf(stderr, NULL, _IONBF, 0); // stderr no buffer
}
string STDIORedirectNative::read()
{
ssize_t res = ::read(_filedes[0], _buf, 8192);
string data;
switch (res)
{
case 0:
return data; // stream finished, just return empty string
case -1:
throw std::runtime_error("read failed");
break;
default:
data = string(_buf, res); // copy buf to string and return
return data;
}
}
void STDIORedirectNative::close()
{
::close(_filedes[0]);
::close(_filedes[1]);
}
void STDIORedirectNative::testPrint(const char* toPrint)
{
// std::cout<<"printing "<<toPrint<<std::endl;
printf("%s", toPrint);
// fflush(stdout);
}