c++ - In a signal handler, how to know where the program is interrupted? -


on x86 (either 64-bit or 32-bit) linux -- example:

void signal_handler(int) {    // want know program interrupted ... }  int main() {     ...     signal(sigalrm, signal_handler);     alarm(5);     ...     printf(...); <------- @ point, trigger signal_handler     ... } 

in signal_handler, how can know interrupted @ printf in main()?

use sigaction sa_siginfo set in sa_flags.

prototype code:

#define _gnu_source 1  /* pick reg_rip */ #include <stdio.h> #include <signal.h> #include <assert.h>  static void handler(int signo, siginfo_t *info, void *context) {     const ucontext_t *con = (ucontext_t *)context;      /* know, never call printf signal handler.  meh. */     printf("ip: %lx\n", con->uc_mcontext.gregs[reg_rip]); }  int main(int argc, char *argv[]) {     struct sigaction sa = { };     sa.sa_flags = sa_siginfo;     sa.sa_sigaction = handler;     assert(sigaction(sigint, &sa, null) == 0);     (;;);     return 0; } 

run , hit ctrl-c. (use ctrl-\ terminate...)

this x86_64. 32-bit x86, use reg_eip instead of reg_rip.

[edit]

of course, if in library function (like printf) or system call (like write), rip/eip register might point somewhere funny...

you might want use libunwind crawl stack.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -