【问题标题】:ptrace(), how can i stop getting traced in child process?ptrace(),我怎样才能停止在子进程中被跟踪?
【发布时间】:2024-10-14 05:50:02
【问题描述】:

我只想跟踪 C 程序的一部分以进行系统调用。我正在使用带有 PTRACE_TRACEME 选项的 ptrace() 来开始跟踪。如何在几行代码后阻止此过程被跟踪。我正在尝试使用 PTRACE_DETACH 但它不起作用?

主要的.C文件是:

#include<stdio.h>
#include<unistd.h>
#include<sys/ptrace.h>
#include<signal.h>

int display(char *p);
int main()
{
    puts("Before Display\n");   
    display("hello");
    puts("After Display\n");
    return 0;
}

int display(char *p)
{
    ptrace(PTRACE_TRACEME, 0, NULL, NULL);
    raise(SIGCONT);
    puts("interception");
    ptrace(PTRACE_DETACH, 0, NULL, NULL);
    return 0;
}

父进程的代码是:

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/reg.h>   /* For constants ORIG_EAX etc */
#include <stdio.h>
int main()
{   pid_t child;
    int status;
    long orig_eax;
    child = fork();
    if(child == 0) 
    {
        execl("/home/kashi/Documents/write", "write", NULL);
    }
    else {
      while(1)
      {
        wait(&status);
          if(WIFEXITED(status))
              break;
        orig_eax = ptrace(PTRACE_PEEKUSER,
                          child, 4 * ORIG_EAX,
                          NULL);
        printf("The child made a "
               "system call %ld\n", orig_eax);
       ptrace(PTRACE_SYSCALL, child, NULL, NULL);
       }
    }
    return 0;
}

【问题讨论】:

    标签: c linux gcc ptrace


    【解决方案1】:

    你不能从被跟踪的过程中做到这一点。

    PTRACE_TRACEME唯一在跟踪过程中有意义的请求。 PTRACE_DETACH 和其他所有必须在跟踪过程中使用。

    被追踪者可以与追踪者交流,并礼貌地要求它分离。没有专门针对此的ptrace 请求。被跟踪者可以例如raise(SIGCONT),tracer会观察它并发出PTRACE_DETACH

    【讨论】:

    • 感谢您解除疑问。您能否为 ptrace() 及其使用提供一些好的参考。