00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 #include "../global.hpp"
00016
00017 #include "input_stream.hpp"
00018
00019 #ifndef _WIN32
00020
00021 #include <algorithm>
00022 #include <iostream>
00023 #include <fcntl.h>
00024 #include <sys/types.h>
00025 #include <sys/stat.h>
00026 #include <unistd.h>
00027
00028 #endif
00029
00030 input_stream::input_stream(const std::string& path) : fd_(-1), path_(path)
00031 {
00032 #ifndef _WIN32
00033 if(path == "") {
00034 return;
00035 }
00036
00037 const int res = mkfifo(path.c_str(),0600);
00038 if(res != 0) {
00039 std::cerr << "could not make fifo at '" << path << "'\n";
00040 }
00041
00042 fd_ = open(path.c_str(),O_RDONLY|O_NONBLOCK);
00043
00044 if(fd_ == -1) {
00045 std::cerr << "failed to open fifo at '" << path << "'\n";
00046 } else {
00047 std::cerr << "opened fifo at '" << path << "'. Server commands may be written to this file.\n";
00048 }
00049 #endif
00050 }
00051
00052 input_stream::~input_stream()
00053 {
00054 #ifndef _WIN32
00055 stop();
00056 #endif
00057 }
00058
00059 void input_stream::stop()
00060 {
00061 #ifndef _WIN32
00062 if(fd_ != -1) {
00063 close(fd_);
00064 unlink(path_.c_str());
00065 fd_ = -1;
00066 }
00067 #endif
00068 }
00069
00070 bool input_stream::read_line(std::string& str)
00071 {
00072 #ifndef _WIN32
00073 if(fd_ == -1) {
00074 return false;
00075 }
00076
00077 const size_t block_size = 4096;
00078 char block[block_size];
00079
00080 const size_t nbytes = read(fd_,block,block_size);
00081 std::copy(block,block+nbytes,std::back_inserter(data_));
00082
00083 const std::deque<char>::iterator itor = std::find(data_.begin(),data_.end(),'\n');
00084 if(itor != data_.end()) {
00085 str.resize(itor - data_.begin());
00086 std::copy(data_.begin(),itor,str.begin());
00087 data_.erase(data_.begin(),itor+1);
00088 return true;
00089 } else {
00090 return false;
00091 }
00092 #else
00093 return false;
00094 #endif
00095 }