程序中止时自动关闭 boost::filtering_stream

Closing boost::filtering_stream automatically when a program is aborted

本文关键字:boost filtering stream 程序      更新时间:2023-10-16

我想使用boost::iostreams来压缩日志文件,并希望在所有情况下都能成功存储日志。当程序因断言失败而中止时,是否可以自动重置boost::filtering_stream类的对象?

#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filtering_stream.hpp>
namespace io = boost::iostreams;
int main() {
io::filtering_ostream out;
out.push(io::gzip_compressor());
out.push(io::file_sink("my_file.txt.gz"));
for (auto i = 0; i < 100; ++i) {
if (i > 50) {
// Can I flush the stream without explicitly calling
// filtering_ostream::reset()?
// out.reset();
assert(false);
}
out << i << 'n';
}
}

失败时,assert调用abort(https://en.cppreference.com/w/cpp/utility/program/abort(,这会跳过堆栈展开,因此不调用析构函数。这有效地为您提供了为 SIGABRT 添加信号处理程序的选项。不过,这可能会变得非常混乱,因为您必须将这些信号与日志记录纠缠在一起,这可能会很脆弱。

作为替代方案,我会提出这个特定要求的理由以供讨论。断言用于验证内部状态,如果它们检测到任何错误,则除了终止并可能使用调试器进行事后检查外,别无他法。要求任何特定行为(例如刷新日志(似乎是矫枉过正。

也许,还有其他选择。如果使用 IPC 转发日志记录信息,则可以在单独的进程中实现压缩。如果程序由于断言失败而中止,则日志将保持不变。