// Build with: gcc trace.c -o trace -lpthread // Usage trace [-f ] Option -f forks the tracing process before attaching to child thread #include #include #include #include #include #include #include #include pthread_t threadPid=0; void *threadFunc(void* dummy) { threadPid=syscall(__NR_gettid); while(1) { printf("Thread is running with pid %d\n",threadPid); sleep(1); } } int main (int argc,char** argv) { printf("Parent pid: %d\n",getpid()); pthread_t thread; if (pthread_create(&thread, NULL, &threadFunc, NULL) == -1) { perror("pthread_create:"); return 10; } sleep(1); pid_t childPid; if(argc==2 && strcmp(argv[1],"-f")==0 &&( childPid=fork()) > 0) { printf("Forking process for PTRACE_ATTACH, waitig for\n"); int status; waitpid(childPid,&status,0); if( WIFEXITED(status) ) { printf("Child terminated normally\n"); } return 0; } printf("Tracing threadPid %d.\n",threadPid); if(ptrace(PTRACE_ATTACH,threadPid,NULL,NULL)!=-1) { int status; if(waitpid(threadPid, &status, WUNTRACED|__WALL) == threadPid) { if(ptrace(PTRACE_DETACH,threadPid,NULL,NULL)!=-1) { printf("Process %d attaching/detaching was sucessful!\n"); } else { perror("PTRACE_ATTACH:"); } } else { perror("waitthreadPid:"); printf("status:%d errno:%d\n",status,errno); } } else { perror("PTRACE_ATTACH: "); } return 0; }