ptrace example 跟踪系统调用


Ref:嵌入式系统中进程间通信的监视方法

example代码略有改动:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <sys/user.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <linux/net.h>

int main (int argc, char argv[])
{
    int status;
    int syscall_entry = 0;
    int traced_process;
    struct user_regs_struct u_in;

    traced_process = atoi(argv[1]); /
从命令行得到监视进程的PID /
    ptrace(PTRACE_ATTACH, traced_process, NULL, NULL);
    wait(&status);    /
等待被监视进程状态变化 /
    ptrace(PTRACE_SYSCALL, traced_process, NULL, NULL);
    while (1) {
        /
等待被监视程序调用系统调用或是发生其它状态变化 /
        wait(&status);

        /
如果被监视进程退出,函数返回真。程序退出 /
        if ( WIFEXITED(status) )
            break;

        ptrace(PTRACE_GETREGS, traced_process, 0, &u_in);
//        if (u_in.orig_eax == 102 && u_in.ebx == SYS_RECVFROM) {
        if (u_in.orig_eax == 102) {
            if (syscall_entry == 0) { /
syscall entry /
                syscall_entry = 1;
                printf("call sys_socketcall(%d)n", u_in.ebx);
            }
            else { /
Syscall exit /
                printf("exit sys_socketcall(%d)n", u_in.ebx);
                syscall_entry = 0;
            }
        }
        ptrace(PTRACE_SYSCALL, traced_process, NULL, NULL);
    } /
while /

    return 0;
} /
main */








end