守护进程使C ++ ostream保持打开状态

时间:2014-03-15 18:09:49

标签: c++ boost posix

我用C ++编写的code需要守护自己。按照惯例,它遍历所有打开的文件描述符,将它们全部关闭。有一些例外,其中一个是用于调试日志记录的文件描述符。

当我遇到问题时,我目前正在将代码转换为Boost :: log基础架构。我无法知道流的文件描述符是什么。

我已经accepted我无法直接从流中获取文件描述符。我有一些非常ugly的解决方法,而且我总是可以重新实现输出流,但这些都看起来非常有效,但收效甚微。

这些真的是我的选择吗?有什么我可能会失踪吗?

谢谢, Shachar

1 个答案:

答案 0 :(得分:1)

我说"这一切看起来都很有效,但收获很少......

再一次,加强救援。重新实施streambuf几乎是一个班轮:

static ios::file_descriptor_sink log_file;
static ios::stream_buffer<decltype(log_file)> log_streambuf;

void init_log()
{
    int fd = open(file_name, O_WRONLY|O_CREAT|O_APPEND, 0666);
    log_file = std::move( ios::file_descriptor_sink(fd, ios::close_handle) );

    // Allocate a log sink
    typedef logging::sinks::synchronous_sink< logging::sinks::text_ostream_backend > text_sink;
    boost::shared_ptr< text_sink > sink = boost::make_shared< text_sink >();

    // Add a stream to write log to
    log_streambuf.open(log_file);
    sink->locked_backend()->add_stream( boost::make_shared<std::ostream>( &log_streambuf ) );
    sink->locked_backend()->auto_flush(flush);

    // Register the sink in the logging core
    logging::core::get()->add_sink(sink);
}

它的主要部分:

  • 使用boost :: iostreams :: file_descriptor_sink来跟踪文件描述符
  • 使用boost :: iostreams :: stream_buffer将其转换为流缓冲区
  • 使用std :: ostream的stream_buffer构造函数创建ostream

只要保留origin file_descriptor实例,您就会知道日志的代码文件描述符是什么。

Shachar