Skip to content

Instantly share code, notes, and snippets.

@ben-cohen
Created May 14, 2018 16:50
Show Gist options
  • Save ben-cohen/55a7e5fc38d607fa6c8332a3d5b4c87a to your computer and use it in GitHub Desktop.
Save ben-cohen/55a7e5fc38d607fa6c8332a3d5b4c87a to your computer and use it in GitHub Desktop.
Ptrace child process without calling exec()
/*
* ptrace_without_exec: Ptrace child process without calling exec()
*
* Compile using:
* gcc -o ptrace_without_exec ptrace_without_exec.c -ggdb -Wall
*
* Ben Cohen, May 2018.
*/
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
long some_value = 0;
int main(int argc, char **argv)
{
pid_t child_pid = fork();
if (child_pid == 0)
{
/* CHILD PROCESS */
pid_t parent = getppid();
some_value = 0x1234abcd;
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
/* Have the child send itself a signal */
raise(SIGCONT);
/* Hang around until the parent disappears */
while (parent == getppid())
sleep(1);
exit(0);
}
else if (child_pid < 0)
{
perror("fork() didn't work");
exit(1);
}
/* PARENT PROCESS */
/* Wait for child to change state (should really check that the child
* hasn't exited) */
wait(NULL);
errno = 0;
long ret = ptrace (PTRACE_PEEKDATA, child_pid, &some_value, NULL);
if (ret == -1 && errno != 0)
{
perror("ptrace() didn't work");
exit(1);
}
printf("Got %#lx\n", ret);
exit(0);
}
/*
* vi:ts=8 sw=8 noet:
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment