为什么ptrace无法识别该功能?

use*_*764 3 c ptrace

我无法弄清楚为什么每次运行它时函数都会返回"No such process"错误消息,但只是使用相同的内联指令会产生所需的输出.

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

void getregs(pid_t proc, struct user_regs_struct *regs);

int main() {
        pid_t proc = fork();

        if(proc == 0) {
                if(ptrace(PTRACE_TRACEME, 0, NULL, NULL) == -1) {
                       perror("traceme");
                       exit(0);
                }

                if(execl("child", "child", NULL) == -1) {
                       perror("execl");
                       exit(0);
                }
        } else {
                wait(&proc);
                struct user_regs_struct regs;
                ptrace(PTRACE_GETREGS, proc, NULL, &regs);
                printf("eax: %08x\n", (unsigned int)regs.eax);
                getregs(proc, &regs);
                ptrace(PTRACE_CONT, proc, NULL, NULL);
        }

        return 0;
}

void getregs(pid_t proc, struct user_regs_struct *regs) {
        if(ptrace(PTRACE_GETREGS, proc, NULL, &regs) == -1) {
                perror("GETREGS");
                exit(1);
        }

        printf("eax: %08x\n", (unsigned int)regs->eax);
}
Run Code Online (Sandbox Code Playgroud)

当我跑这个我得到

~$ ./tracer 
eax: 0000002f 
GETREGS: No such process
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会getregs()返回该错误.它几乎就像是超出了某些范围?

此外,有点不相关的东西:0000002f无论我尝试什么过程,EAX始终设置为execl().这很自然吗?我不知道我是否正确分配了孩子的过程.我是否需要就此问题提出新问题?

Hal*_*oum 5

您遇到此错误是因为您proc通过将其地址传递给wait(2)系统调用来修改变量中包含的进程标识符(PID)的值.

该wait系统调用会改变的价值proc与您的孩子的过程终止时的返回状态.因此,当您在ptrace 使用中引用子进程时proc,其值可能无效并且不引用任何现有进程.

而作为@lornix注意到,请确保您传递正确指针ptrace的getregs函数.