程序中止时自动关闭 boost::filtering_stream
Closing boost::filtering_stream automatically when a program is aborted
我想使用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 转发日志记录信息,则可以在单独的进程中实现压缩。如果程序由于断言失败而中止,则日志将保持不变。
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- boost::进程间消息队列引发错误
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- cmake如何在fedora工作站中找到boost静态库包
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- Boost Graph Library,修复节点大小
- 什么是"#include <boost/functional/hash.hpp> "?
- 基于boost的程序的静态链接——zlib问题
- C++:如何在CLion IDE中安装Boost
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在boost beast http请求中设置http头
- Boost Spirit,获取迭代器内部语义动作
- boost::asio::steady_timer()与sleep()我应该使用哪一个
- boost::asio如何生成多个协同程序,然后加入它们
- 当我尝试使用 sstream 和分面将 Boost Time_duration转换为字符串时,我没有得到所需的格式
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 使用Boost Interprocess创建托管共享内存需要很长时间
- Boost::posix_time::ptime舍入到给定的分钟数
- boost xml parsingl将xml的路径作为变量发送