IBR-DTNSuite  0.10
appstreambuf.cpp
Go to the documentation of this file.
1 /*
2  * appstreambuf.cpp
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #include "ibrcommon/config.h"
23 #include "ibrcommon/appstreambuf.h"
24 
25 namespace ibrcommon
26 {
28  : m_buf( BUF_SIZE+1 )
29  {
30  // execute the command
31  if (mode == MODE_READ)
32  {
33  setg(0, 0, 0);
34  _handle = popen(command.c_str(), "r");
35  }
36  else
37  {
38  setp( &m_buf[0], &m_buf[0] + (m_buf.size() - 1) );
39  _handle = popen(command.c_str(), "w");
40  }
41  }
42 
44  {
45  // close the handle
46  pclose(_handle);
47  }
48 
49  std::char_traits<char>::int_type appstreambuf::underflow()
50  {
51  // read the stdout of the process
52  size_t ret = 0;
53 
54  if (feof(_handle))
55  return std::char_traits<char>::eof();
56 
57  ret = fread(&m_buf[0], sizeof(char), m_buf.size(), _handle);
58 
59  // Since the input buffer content is now valid (or is new)
60  // the get pointer should be initialized (or reset).
61  setg(&m_buf[0], &m_buf[0], &m_buf[0] + ret);
62 
63  return std::char_traits<char>::not_eof((unsigned char) m_buf[0]);
64  }
65 
67  {
68  int ret = std::char_traits<char>::eq_int_type(this->overflow(std::char_traits<char>::eof()),
69  std::char_traits<char>::eof()) ? -1 : 0;
70 
71  return ret;
72  }
73 
74  std::char_traits<char>::int_type appstreambuf::overflow( std::char_traits<char>::int_type m )
75  {
76  char *ibegin = pbase();
77  char *iend = pptr();
78 
79  // if there is nothing to send, just return
80  if ( iend <= ibegin ) return std::char_traits<char>::not_eof(m);
81 
82  size_t avail_data = (iend - ibegin);
83 
84  // mark the buffer as free
85  setp( &m_buf[0], &m_buf[0] + (m_buf.size() - 1) );
86 
87  if(!std::char_traits<char>::eq_int_type(m, std::char_traits<char>::eof())) {
88  *iend++ = std::char_traits<char>::to_char_type(m);
89  }
90 
91  // write the data
92  if (fwrite(pbase(), sizeof(char), avail_data, _handle) != avail_data)
93  {
94  return std::char_traits<char>::eof();
95  }
96 
97  return std::char_traits<char>::not_eof(m);
98  }
99 }