1.1 背景
有时候需要获取线程id,结合strace工具,跟踪线程内部系统调用过程,但pthread_self()获取到的线程id是在程序内部用的,这里所有说的线程id,指的是能通过pstree查看,ps,htop查看的线程id,有时候用strace跟踪某个线程的内部系统调用,因此获取线程id,这个线程id对应程序和内核来说都是唯一的。
*1.2 获取方法 *
#include <sys/syscall.h>
syscall(SYS_gettid) 这个函数的返回值即是线程id,对于内核来说,是唯一的。
1.3 获取线程id之后,用strace跟踪线程,查看线程的系统调用过程
测试例子:
#include <stdio.h>
#include <stdarg.h>
#include <sys/syscall.h>
#include <pthread.h>
#include <string.h>
#include <time.h>
void log_file(char *s)
{
FILE *fd = NULL;
fd = fopen("/tmp/Log.txt", "a+");
time_t cur_time;
struct tm *local_time;
cur_time = time(NULL);
local_time = localtime(&cur_time);
if (fd == NULL)
{
return;
}
fprintf(fd, "%d:%d:%d:%s ", local_time->tm_hour,local_time->tm_min,local_time->tm_sec,s);
fprintf(fd, "\r\n");
fprintf(fd, "\r\n");
fclose(fd);
}
void get_process_pid(const char *function)
{
char msg[1024] = {0};
sprintf(msg,"%s,pid:%d",function,syscall(SYS_gettid));
log_file(msg);
}
void *thread_one(void *arg)
{
while(1)
{
sleep(1);
write(1,"thread_one",strlen("thread_one"));
write(1,"\n",1);
}
pthread_exit(NULL);
}
void *thread_two(void *arg)
{
while(1)
{
sleep(1);
write(1,"thread_two",strlen("thread_two"));
write(1,"\n",1);
}
pthread_exit(NULL);
}
int main(void)
{
pthread_t thread_one_id;
pthread_t thread_two_id;
pthread_create(&thread_one_id,NULL,thread_one,NULL);
pthread_create(&thread_two_id,NULL,thread_two,NULL);
while(1)
{
pthread_join(thread_one_id,NULL);
pthread_join(thread_two_id,NULL);
sleep(1);
}
return 0;
}
gcc test.c -lpthread
./a.out
查看日志文件,各线程id,及对应的函数为:
1.4 strace -p pid 跟踪系统调用
或者:
top -H -p pidof a.out
htop