how does ptrace catch fork's system call?

I try to use ptrace to catch child process system call id such as execve(11) or fork(2).

my code is here.

#include <sys/syscall.h>
#include <sys/reg.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int main(){
    pid_t pid;
    if ((pid = fork()) == 0){
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        pid_t t = fork();
    } else{
        int status;
        struct rusage resource;
        while (true){
            wait4(pid, &status, 0, &resource);
            if (WIFEXITED(status)) break;
            int syscall = ptrace(PTRACE_PEEKUSER, pid, 4 * ORIG_EAX, NULL);
            if (syscall == SYS_execve) printf("%dn", syscall);
            ptrace(PTRACE_SYSCALL, pid, NULL, NULL);
        }
    }
    return 0;
}

In my opinion, the program should print "2" to screen(because system call "fork" id is 2), but I got nothing after the program finished. Can someone explain me about it?


If your program has exited normally, then

if (WIFEXITED(status)) break;

this statement might have caused not printing 2 as it is taking it out of the loop.

Please see this statement.

链接地址: http://www.djcxy.com/p/66376.html

上一篇: 如何实现在线沙箱

下一篇: ptrace如何捕获fork的系统调用?