Created
February 1, 2015 23:05
-
-
Save matthiasvegh/e0725ea0ae3c4230784f to your computer and use it in GitHub Desktop.
Redirect Cerr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <sys/epoll.h> | |
struct Redirecter { | |
int writeFd, readFd; | |
Redirecter() { | |
int pipeFds[2]; | |
int& readFd = pipeFds[0]; | |
int& writeFd = pipeFds[1]; | |
int result = pipe(pipeFds); | |
this->readFd = readFd; | |
this->writeFd = writeFd; | |
dup2(writeFd, 2); | |
int defaultFlags = fcntl(readFd, F_GETFL, 0); | |
fcntl(readFd, F_SETFL, defaultFlags | O_NONBLOCK); | |
} | |
}; | |
void* actor(void*); | |
struct RedirecterService { | |
Redirecter r; | |
static std::string readAvailable(int fd) { | |
std::string result; | |
char buf[15]; | |
memset(&buf, 0, sizeof(buf)); | |
int length; | |
while( (length = read(fd, &buf, sizeof(buf))) >0) { | |
result.append(buf, length); | |
} | |
return result; | |
} | |
void startActor() { | |
pthread_t pt; | |
pthread_create(&pt, 0, actor, this); | |
pthread_detach(pt); | |
} | |
}; | |
void* actor(void* r_) { | |
RedirecterService& r = *reinterpret_cast<RedirecterService*>(r_); | |
std::string line; | |
char buf[15]; | |
int epoll_fd = epoll_create(1); | |
struct epoll_event ev; | |
ev.events = EPOLLIN; | |
ev.data.fd = r.r.readFd; | |
struct epoll_event ev2; | |
epoll_ctl(epoll_fd, EPOLL_CTL_ADD, r.r.readFd, &ev); | |
for(;;) { | |
memset(&buf, 0, sizeof(buf)); | |
int nfds = epoll_wait(epoll_fd, &ev2, 1, -1); | |
std::cout<<ev2.data.fd<<std::endl; | |
std::cout<<"CERR "<<RedirecterService::readAvailable(r.r.readFd)<<std::endl; | |
} | |
return 0; | |
} | |
int main() { | |
RedirecterService r; | |
r.startActor(); | |
for(;;) { | |
std::string input; | |
std::cin>>input; | |
std::cerr<<input; | |
} | |
pthread_exit(0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment