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