获取线程id-->strace跟踪线程系统调用

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

转载于:https://my.oschina.net/u/4149215/blog/3075947

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值