我正在尝试使用PTRACE_TRACEME来跟踪子进程:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/user.h>
int main(int argc, char *argv[]) {
pid_t child_pid;
int status;
struct user_regs_struct regs;
if (argc < 2) {
fprintf(stderr, "Usage: %s program [arguments]\n", argv[0]);
exit(1);
}
child_pid = fork();
if (child_pid == 0) {
/* Child process */
/* Allow parent to trace this process */
if (ptrace(PTRACE_TRACEME, 0, NULL, NULL) == -1) {
perror("ptrace3");
exit(1);
}
/* Replace child process with specified program */
execvp(argv[1], &argv[1]);
/* If execvp returns, there was an error */
perror("execvp");
exit(1);
}
else if (child_pid > 0) {
/* Parent process */
/* Attach to child process */
if (ptrace(PTRACE_ATTACH, child_pid, NULL, NULL) == -1) {
perror("ptrace5");
exit(1);
}
/* Wait for child process to start */
waitpid(child_pid, &status, 0);
/* Continue running child process */
if (ptrace(PTRACE_CONT, child_pid, NULL, NULL) == -1) {
perror("ptrace4");
exit(1);
}
/* Wait for child process to stop */
waitpid(child_pid, &status, 0);
/* Do something with registers */
/* Detach from child process */
if (ptrace(PTRACE_DETACH, child_pid, NULL, NULL) == -1) {
perror("ptrace");
exit(1);
}
} else {
/* Fork failed */
perror("fork");
exit(1);
}
return 0;
}
我在PTRCAE_TRACEME上得到了错误:
ptrace3: Operation not permitted
如果我在父进程的if条件PTRACE_ATTACH
和waitpid(child_pid, &status, 0);
之间切换:
/* Wait for child process to start */
waitpid(child_pid, &status, 0);
/* Attach to child process */
if (ptrace(PTRACE_ATTACH, child_pid, NULL, NULL) == -1) {
perror("ptrace5");
exit(1);
}
我在PTRACE_ATTACH上得到错误:
ptrace5: Operation not permitted
因为我知道这与安全功能有关,我试图将ptrace_scope更改为0,并检查SELinux是否禁用。此外,我没有在Docker中使用,我的dito是Ubuntu 22.04。感谢您的帮助!
1条答案
按热度按时间odopli941#
这是因为linux的安全系统。这可以解决:
**1.**通过sudo运行。
**2.**更改OS内核配置以允许调试进程。为此,您可以更改/proc/sys/kernel/yama/ptrace_scope参数的值。
**3.**使用其他调试函数,如PTRACE_SEIZE,可以更安全,不需要root权限。