1. 程式人生 > >linux之通過ptrace獲取指定pthread執行緒的暫存器資訊

linux之通過ptrace獲取指定pthread執行緒的暫存器資訊

#include <stdio.h>
#include <unistd.h> //for sleep
#include <stdlib.h> //for exit
#include <pthread.h>//for pthread
#include <errno.h>  //for errno
#include <sys/syscall.h> //for gettid
#define gettid() syscall(__NR_gettid)

void *func(void *para)
{
	printf("Hello world.\n");
	printf("child process tid: %u\n", gettid());
	sleep(-1);	// 該程序一直sleep,等待
	return NULL;
}

int main()
{ 
	pthread_t tid;
	int ret = pthread_create(&tid, NULL, func, NULL);
	if (ret != 0)
	{   
		exit(errno);
	}   
	printf("parent process pid: %u\n", getpid());

	pthread_join(tid, NULL);
	return 0;
}

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/user.h> /**//* For user_regs_struct 
                             etc. */
#include <stdio.h>
#include <stdlib.h>

//http://www.cnblogs.com/wangkangluo1/archive/2012/06/05/2535484.html
//http://blog.csdn.net/sealyao/article/details/6710772
//通過ptrace獲取指定pthread執行緒的暫存器資訊:
int main(int argc, char *argv[])
{ 
	pid_t traced_process;
	struct user_regs_struct regs;
	long ins;
	if (argc != 2)
	{
			printf("Usage: %s <pid to be traced> ",
				argv[0],
				argv[1]);
			exit(1);
	}
	traced_process = atoi(argv[1]);
	ptrace(PTRACE_ATTACH,traced_process, 
		NULL,
		NULL);
	wait(NULL);
	ptrace(PTRACE_GETREGS,traced_process, 
		NULL,
		&regs);
	ins = ptrace(PTRACE_PEEKTEXT,
		traced_process, 
		regs.eip,
		NULL);
	printf("EIP: %lx Instruction executed: %lx \n", 
		regs.eip,
		ins);
	ptrace(PTRACE_DETACH,
		traced_process, NULL,NULL);
	return 0;
}