简体   繁体   English

用于sigsegv的c ++ linux监视进程

[英]c++ linux monitor processes for sigsegv

I want to write a c++ program for linux which monitors all processes running and write to a log file when any of those processes crashes due to sigsegv. 我想为linux编写一个c ++程序,它监视所有正在运行的进程并在由于sigsegv导致任何进程崩溃时写入日志文件。

Is it possible to do this and if so what should I learn in order to implement it in c++? 是否可以这样做,如果是这样,我应该学习什么才能在c ++中实现它?

Trying to monitor all processes on the system would be onerous. 试图监控系统上的所有进程将是繁重的。 If you are interested in SIGSEGV specifically, you might want to consider installing yourself as core dump handler instead. 如果您对SIGSEGV特别感兴趣,可能需要考虑将自己安装为核心转储处理程序。 It will not catch processes that have asked to have core dumps disabled ( ulimit -c 0 ), but you will get all others. 它不会捕获要求禁用核心转储的进程( ulimit -c 0 ),但是您将获得所有其他进程。

echo "|usr/local/sbin/crashcollector" >/proc/sys/kernel/core_pattern

Now /usr/local/sbin/crashcollector will be called with the core dump on its standard input every time a process crashes. 现在/usr/local/sbin/crashcollector将在每次进程崩溃时使用其标准输入上的核心转储进行调用。 This program can do whatever it wants, such as save the core dump and/or notify something else. 该程序可以执行任何操作,例如保存核心转储和/或通知其他内容。

I expect you are going to catch all processes crash event. 我希望你能抓住所有进程崩溃事件。 Using ptrace is an approach, but it is very complex, you need to trace all processes and attach to new processes created later, also you'll hit performance penalty. 使用ptrace是一种方法,但它非常复杂,您需要跟踪所有进程并附加到以后创建的新进程,您也会遇到性能损失。

You can catch all processes crash event by hook coredump : 您可以通过钩子coredump捕获所有进程崩溃事件:

echo "|yourcoredumphook" > /proc/sys/kernel/core_pattern

this will enable coredump hook, when a process terminated, yourcoredumphook will be started as root with coredump sent through stdin, so you can figure out which process terminated by analysis the coredump 这将启用coredump hook,当进程终止时, yourcoredumphook将以root yourcoredumphook启动,coredump通过stdin发送,这样你就可以通过分析coredump找出终止哪个进程

You probably want to use ptrace for this. 您可能想要使用ptrace Take a look at this question: how to intercept linux signals ? 看看这个问题: 如何拦截linux信号? (in C) (在C中)

I imagine doing this for all processes would require a re-implementation of init, or perhaps a system that monitors the sys directory to call ptrace for each process. 我想这对所有进程执行此操作需要重新实现init,或者可能需要一个监视sys目录的系统来为每个进程调用ptrace

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM