10 #include <sys/ptrace.h>
14 #if defined(PTRACE_ATTACH)
15 #define ATTACH_REQUEST PTRACE_ATTACH
16 #define DETACH_REQUEST PTRACE_DETACH
17 #elif defined(PT_ATTACH)
18 #define ATTACH_REQUEST PT_ATTACH
19 #define DETACH_REQUEST PT_DETACH
21 #error "Unsupported platform"
24 bool writePid (const char* file_name
, const pid_t pid
)
26 char *tmp_file_name
= (char *)malloc(strlen(file_name
) + 16);
27 strcpy(tmp_file_name
, file_name
);
28 strcat(tmp_file_name
, "_tmp");
29 int fd
= open (tmp_file_name
, O_CREAT
| O_WRONLY
| O_TRUNC
, S_IRUSR
| S_IWUSR
);
32 fprintf (stderr
, "open(%s) failed: %s\n", tmp_file_name
, strerror (errno
));
37 snprintf (buffer
, sizeof(buffer
), "%ld", (long)pid
);
40 if (write (fd
, buffer
, strlen (buffer
)) == -1)
42 fprintf (stderr
, "write(%s) failed: %s\n", buffer
, strerror (errno
));
47 if (rename (tmp_file_name
, file_name
) == -1)
49 fprintf (stderr
, "rename(%s, %s) failed: %s\n", tmp_file_name
, file_name
, strerror (errno
));
57 void signal_handler (int)
61 int main (int argc
, char const *argv
[])
65 fprintf (stderr
, "invalid number of command line arguments\n");
69 const pid_t pid
= fork ();
72 fprintf (stderr
, "fork failed: %s\n", strerror (errno
));
78 // Make pause call to return when a signal is received. Normally this happens when the
79 // test runner tries to terminate us.
80 signal (SIGHUP
, signal_handler
);
81 signal (SIGTERM
, signal_handler
);
82 if (ptrace (ATTACH_REQUEST
, pid
, NULL
, 0) == -1)
84 fprintf (stderr
, "ptrace(ATTACH) failed: %s\n", strerror (errno
));
88 if (writePid (argv
[1], pid
))
89 pause (); // Waiting for the debugger trying attach to the child.
91 if (ptrace (DETACH_REQUEST
, pid
, NULL
, 0) != 0)
92 fprintf (stderr
, "ptrace(DETACH) failed: %s\n", strerror (errno
));
97 if (waitpid (pid
, &status
, 0) == -1)
98 fprintf (stderr
, "waitpid failed: %s\n", strerror (errno
));
106 printf ("Exiting now\n");