How to do memory check on a daemon program?

2019-03-19 22:27发布

问题:

I have written a C++ application, that runs forever until terminated manually. It monitors other important applications. As a result my Daemon application should not go down. Keeping that in mind, I want to see if there are any memory leaks in my application. I used valgrind but since this application keeps running forever the valgrind does not exit. if I do a control - C then I don't get complete info from the valgrind logfile.

Is there a tool that can do what Valgrind does?

回答1:

I believe you can connect gdb to a running valgrind process, and instruct it to run a leak check explicitly.

I haven't tried this, just seen it in the docs.

In case of link breakage:

Connecting GDB to a Valgrind gdbserver

$ valgrind --tool=memcheck --vgdb=yes --vgdb-error=0 ./prog

(the error parameter is the number of errors before the gdbserver becomes active: zero means it starts running right away).

Then start gdb on your program and connect to the remote target

$ gdb ./prog
(gdb) target remote | vgdb

and to trigger the check

(gdb) monitor leak_check full reachable any

See your docs or the linked ones for full details.



回答2:

The most obvious way is to add a clean way to shutdown the daemon, perhaps by catching the SIGTERM signal, and shutting down. Otherwise any memory in use (legitimately) when you kill the daemon will complicate the results.

Alternatively there are valgrind client requests VALGRIND_DO_LEAK_CHECK VALGRIND_DO_ADDED_LEAK_CHECK VALGRIND_DO_CHANGED_LEAK_CHECK which you could trigger in your daemon, perhaps on a timer. Then comparing the results might tell you about any leaks.



回答3:

You cannot detect leaks without exiting at some point. I think you can use valgrind and make the deamon exit after say 5 minutes. Then valgrind will report your leaks. Keep in mind that if your deamon is continuously allocating memory due to a logical flaw in the algorithm, it can still run out of memory without any leaks in the code.