How does ptrace work with 2 different processes?

谁说胖子不能爱 提交于 2019-12-14 04:00:50

问题


I was reading about ptrace on the net and found that a process can request to trace another process by using PTRACE_ATTACH but apparently all the examples available involve the use of fork().

What I want is to have 2 programs - prg1.c and prg2.c where prg2.c should trace prg1.c. I tried using PTRACE_ATTACH in prg2.c but it seems that the call failed - prg2.c couldn't trace prg1.c . How does ptrace work ? Can anybody explain ?

Code for prg1.c :

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

#include <stdlib.h>

int main()
{
    printf("Hello world\n");
    sleep(20);

    execl("/bin/ls", "ls", NULL);
    return 0;
}

Code for prg2.c :

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

#include <stdlib.h>
int main(int argc , char **argv)
{
    int pid = atoi(argv[1]);
    int status;
    if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) == -1) {
        printf("ptrace attach failed!");
        return 0;
    }

wait(&status);
sleep(5);

ptrace(PTRACE_DETACH, pid, NULL, NULL);
return 0;
}

I have included a sleep() to get the pid of prg1's executable(during that time) using ps -af and give it as an input to the executable of prg2.

来源:https://stackoverflow.com/questions/35311767/how-does-ptrace-work-with-2-different-processes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!