mac os父进程单步调试子进程执行了多少条指令
#import <Foundation/Foundation.h>
#import <sys/ptrace.h>
#import <string.h>
void run_target(const char* programname)
{
/* Allow tracing of this process */
if (ptrace(PT_TRACE_ME, 0, 1, 0) < 0) {
perror("ptrace");
return;
}
/* Replace this process's image with the given program */
printf("target started. will run '%s'\n", programname);
execl(programname, programname, 0);
char * error = strerror(errno);
printf("error = %s",error);
}
void run_debugger(pid_t child_pid)
{
int wait_status;
unsigned icounter = 0;
int wait_result = 0;
printf("parent debugger started\n");
/* Wait for child to stop on its first instruction */
waitpid(child_pid, &wait_status, WUNTRACED);
while (WIFSTOPPED(wait_status)) {
printf("while start wait_status = %d\n",wait_status);
icounter++;
/* Make the child execute another instruction */
int result = 0;
result = ptrace(PT_STEP, child_pid, 1, 0);
if (result < 0) {
char * errstr = strerror(errno);
printf("%s\n",errstr);
return;
}
printf("run_debugger icounter=%d,result=%d\n",icounter,result);
/* Wait for child to stop on its next instruction */
//如果返回值为0,那么
wait_result = waitpid(child_pid, &wait_status, WUNTRACED);
if(wait_result != 0)
{
usleep(20);
}
printf("while end wait_result = %d\n",wait_result);
}
printf("the child executed %u instructions\n", icounter);
}
int main(int argc, char** argv)
{
pid_t child_pid;
if (argc < 2) {
fprintf(stderr, "Expected a program name as argument\n");
return -1;
}
child_pid = fork();
if (child_pid == 0)
{
run_target(argv[1]);
}
else if (child_pid > 0)
{
run_debugger(child_pid);
}
else {
perror("fork");
return -1;
}
return 0;
}
不知道为什么要usleep(20),不然就是一直wait,父进程和子进程都不能够退出!

浙公网安备 33010602011771号