是否可以使用C ++流类来缓冲管道中的读取?

时间:2012-08-24 17:35:57

标签: c++ filestream iostream pipe

简而言之,是否可以根据此伪示例所描述的内容从流类中对管道进行缓冲读取。

请忽略您看到的任何迂腐问题(例如不检查错误等);我在我的真实代码中做了所有这些,这只是一个伪问题来解决我的问题。

#include <iostream> // or istream, ifstream, strstream, etc; whatever stream could pull this off
#include <unistd.h>
#include <stdlib.h>
#include <sstream>

void myFunc() {
  int pipefd[2][2] = {{0,0},{0,0}};

  pipe2( pipefd[0], O_NONBLOCK );
  pipe2( pipefd[1], O_NONBLOCK );

  if( 0 == fork() ) {
    close( pipefd[0][1] );
    close( pipefd[1][1] );
    dup2( pipefd[0][0], stdout );
    dup2( pipefd[1][0], stderr );
    execv( /* some arbitrary program */ );
  } else {
    close( pipefd[0][0] );
    close( pipefd[1][0] );

    /* cloudy bubble here for the 'right thing to do'.
     * Obviously this is faulty code; look at the intent,
     * not the implementation.
     */
#ifdef RIGHT_THING_TO_DO
    for( int ii = 0; ii < 2; ++ii ) {
      cin.tie( pipefd[ii][1] );
      do {
        cin.readline( /* ... */ );
      } while( /* ... */ );
    }
#else
    // This is what I'm doing now; it works, but I'm
    // curious whether it can be done more concisely
    do {
      do {
        select( /* ... */ );
        for( int ii = 0; ii < 2; ++ii ) {
          if( FD_SET( fd[ii][1], &rfds ) ) {
            read( fd[ii][1], buff, 4096 );
            if( /* read returned a value > 0 */ ) {
              myStringStream << buff;
            } else {
              FD_CLR( fd[ii][1], &rfds );
            }
          }
        }
      } while( /* select returned a value > 0 */ );
    } while( 0 == waitpid( -1, 0, WNOHANG ) );
#endif
  }
}

修改

以下是如何使用boost::file_descriptor处理管道的简单示例;也应该使用套接字,但没有测试。

这是我编译它的方式:

g++ -m32 -DBOOST_IOSTREAMS_NO_LIB -isystem ${BOOST_PATH}/include \
  ${BOOST_SRC_PATH}/libs/iostreams/src/file_descriptor.cpp blah.cc -o blah

以下是示例:

#include <fcntl.h>
#include <stdio.h>

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>

int main( int argc, char* argv[] ) {
  // if you just do 'using namespace...', there's a
  // namespace collision with the global 'write'
  // function used in the child
  namespace io = boost::iostreams;

  int pipefd[] = {0,0};
  pipe( pipefd, 0 );  // If you use O_NONBLOCK, you'll have to
                      // add some extra checks to the loop so
                      // it will wait until the child is finished.

  if( 0 == fork() ) {
    // child
    close( pipefd[0] ); // read handle
    dup2( pipefd[1], FILENO_STDOUT );
    printf( "This\nis\na\ntest\nto\nmake sure that\nit\nis\working as expected.\n" );
    return 0; // ya ya, shoot me ;p
  }

  // parent

  close( pipefd[1] ); // write handle

  char *buff = new char[1024];
  memset( buff, 0, 1024 );

  io::stream<io::file_descriptor_source> fds(
    io::file_descriptor_source( pipefd[0], io::never_close_handle ) );

  // this should work with std::getline as well
  while(   fds.getline( buff, 1024 )
        && fds.gcount() > 0 // this condition is not enough if you use
                            // O_NONBLOCK; it should only bail if this
                            // is false AND the child has exited
       ) {
    printf( "%s,", buff );
  }

  printf( "\n" );
}

2 个答案:

答案 0 :(得分:5)

确实有。有关如何制作包装文件描述符的std :: streambuf(如从pipe()获得的那些)的书“C ++标准库:教程和参考”中有一个例子。从那里开始创建一个流是微不足道的。

编辑:这是书:http://www.josuttis.com/libbook/

这是一个使用文件描述符的示例输出缓冲区:http://www.josuttis.com/libbook/io/outbuf2.hpp.html

此外,这是一个示例输入缓冲区:http://www.josuttis.com/libbook/io/inbuf1.hpp.html

答案 1 :(得分:1)

您需要可以使用现有文件描述符创建的流,或者创建管道本身的流。不幸的是,没有这种标准的流类型。

您可以自己编写或使用,例如boost::iostreams::file_descriptor

编写自己的东西需要创建basic_streambuf的子类,然后创建一个非常简单的basic_i / ostream子类,它只能保存你的streambuf类并提供方便的构造函数。