Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving gmon.out before killing a process

Tags:

I would like to use gprof to profile a daemon. My daemon uses a 3rd party library, with which it registers some callbacks, then calls a main function, that never returns. I need to call kill (either SIGTERM or SIGKILL) to terminate the daemon. Unfortunately, gprof's manual page says the following:

The profiled program must call "exit"(2) or return normally for the profiling information to be saved in the gmon.out file.

Is there is way to save profiling information for processes which are killed with SIGTERM or SIGKILL ?

like image 452
user1202136 Avatar asked Apr 18 '12 08:04

user1202136


2 Answers

First, I would like to thank @wallyk for giving me good initial pointers. I solved my issue as follows. Apparently, libc's gprof exit handler is called _mcleanup. So, I registered a signal handler for SIGUSR1 (unused by the 3rd party library) and called _mcleanup and _exit. Works perfectly! The code looks as follows:

#include <dlfcn.h> #include <stdio.h> #include <unistd.h>  void sigUsr1Handler(int sig) {     fprintf(stderr, "Exiting on SIGUSR1\n");     void (*_mcleanup)(void);     _mcleanup = (void (*)(void))dlsym(RTLD_DEFAULT, "_mcleanup");     if (_mcleanup == NULL)          fprintf(stderr, "Unable to find gprof exit hook\n");     else _mcleanup();     _exit(0); }  int main(int argc, char* argv[]) {     signal(SIGUSR1, sigUsr1Handler);     neverReturningLibraryFunction(); } 
like image 143
user1202136 Avatar answered Sep 19 '22 17:09

user1202136


You could add a signal handler for a signal the third party library doesn't catch or ignore. Probably SIGUSR1 is good enough, but will either have to experiment or read the library's documentation—if it is thorough enough.

Your signal handler can simply call exit().

like image 35
wallyk Avatar answered Sep 19 '22 17:09

wallyk