[英]Using ptrace to detect debugger
我试图在 Linux 上检测调试器是否附加到我的二进制文件。 我找到了两个解决方案。 一个更简单的:
#include <stdio.h>
#include <sys/ptrace.h>
int main()
{
if (ptrace(PTRACE_TRACEME, 0, 1, 0) == -1)
{
printf("don't trace me !!\n");
return 1;
}
// normal execution
return 0;
}
还有一个:
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
int spc_detect_ptrace(void) {
int status, waitrc;
pid_t child, parent;
parent = getpid();
if (!(child = fork())) {
/* this is the child process */
if (ptrace(PT_ATTACH, parent, 0, 0)) exit(1);
do {
waitrc = waitpid(parent, &status, 0);
} while (waitrc == -1 && errno == EINTR);
ptrace(PT_DETACH, parent, (caddr_t)1, SIGCONT);
exit(0);
}
if (child == -1) return -1;
do {
waitrc = waitpid(child, &status, 0);
} while (waitrc == -1 && errno == EINTR);
return WEXITSTATUS(status);
}
第二种方法比第一种更简单的方法更好吗? 如果是,为什么?
除了 ptrace() 方法外,还可以向 SIGTRAP 发出信号( 如何检测当前进程是否正在由 GDB 运行? )
我会说你的第一种方法更好(并且比 SIGTRAP 更好),因为分叉对于这样的检查来说效率非常低,并且在很多情况下(比如多线程代码)分叉是不可取的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.