1

我正在使用 ptrace 来跟踪子进程。当子进程正常退出时,它工作得很好。但是如果它异常退出,尽管使用了宏 WIFSIGNALED(&status),程序仍会进入无限循环。这是示例子进程:

尝试.c

int main()
   {
      int a=5/0;
   }

这是跟踪程序

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/syscall.h>   /* For SYS_write etc */
#include <sys/reg.h>
#include <signal.h>
int main()
{   
    pid_t child;
    long orig_eax, eax;
    int status,insyscall = 0;
    child = fork();
    if(child == 0)
    {
            ptrace(PTRACE_TRACEME, 0, NULL, NULL);
            execl("./try", "try", NULL);
    }
    else
    {
        siginfo_t sig;
        memset(&sig,0,sizeof(siginfo_t));
        while(1)
        {
            wait(&status);
            if(WIFSIGNALED(status))
            {
                printf("Exiting due to signal\n");
                exit(0);
            }
            if(WIFEXITED(status))
                break;
            orig_eax = ptrace(PTRACE_PEEKUSER,child, 4 * ORIG_EAX, NULL);
            printf("system call number=%ld\n",orig_eax);
            if(insyscall == 0)
            {
                      /* Syscall entry */
                      insyscall = 1;
                      printf("In sys call\n");
            }
            else 
            {
               /* Syscall exit */
                 eax = ptrace(PTRACE_PEEKUSER,child, 4 * EAX, NULL);
                 printf("System call returned with %ld\n", eax);
                 insyscall = 0;
             }
            ptrace(PTRACE_SYSCALL,child, NULL, NULL);
        }
    }
    return 0;
}

为什么没有检测到在不使用 ptrace 时有效的信号?

4

1 回答 1

3

当您 ptrace 进程时,等待将返回任何状态更改。其中之一是当进程即将接收信号时。在信号传递给孩子之前,您的等待将返回。如果这是您想要发生的,您需要使用 PTRACE_CONT 来允许将信号传递给孩子。

Why does it work this way? Well remember, ptrace's main purpose is to be used in implementing debuggers. If you didn't get a chance to intercept signals such as SIGSEGV, the debugger couldn't stop and let you examine the seg fault before the process was torn down.

于 2011-09-18T14:59:39.297 回答