gpt4 book ai didi

c++ - 在信号处理程序中,如何知道程序在哪里被中断?

转载 作者:IT王子 更新时间:2023-10-28 23:59:53 25 4
gpt4 key购买 nike

在 x86(64 位或 32 位)Linux 上 --例如:

void signal_handler(int) {
// want to know where the program is interrupted ...
}

int main() {
...
signal(SIGALRM, signal_handler);
alarm(5);
...
printf(...); <------- at this point, we trigger signal_handler
...
}

在 signal_handler 中,我们如何知道我们在 main() 中的 printf 被中断了?

最佳答案

使用sigaction在 sa_flags 中设置 SA_SIGINFO。

原型(prototype)代码:

#define _GNU_SOURCE 1  /* To pick up 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;

/* I know, never call printf from a 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);
for (;;);
return 0;
}

运行它并按 Ctrl-C。 (使用Ctrl-\终止...)

这是针对 x86_64 的。对于 32 位 x86,使用 REG_EIP 而不是 REG_RIP

[编辑]

当然,如果您实际上是在库函数(如 printf)或系统调用(如 write)中,RIP/EIP 寄存器可能指向某个有趣的地方...

您可能想使用 libunwind爬取堆栈。

关于c++ - 在信号处理程序中,如何知道程序在哪里被中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6768426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com