1、gettid()系统调用作用
gettid() 是一个Linux系统调用,用于获取当前进程的线程ID。在使用此系统调用时,你需要包含 <sys/syscall.h> 头文件,并且可以通过直接调用或使用 syscall() 函数来进行系统调用。
注意:ps 中显示的PID列的值和gettid()的值是一样的
以下是一个简单的示例代码,展示如何使用 gettid() 获取当前线程的ID:
#define _GNU_SOURCE
#include <unistd.h>
#include <sys/syscall.h>
#include <stdio.h>
int main() {
pid_t tid;
// 直接调用gettid()
tid = syscall(SYS_gettid);
printf("当前线程的ID是: %ld\n", (long)tid);
return 0;
}
2、getpid()系统调用定义
/* Thread ID - the internal kernel "pid" */
SYSCALL_DEFINE0(gettid)
{
return task_pid_vnr(current);
}
从系统调用注释解释可以看出,gettid()系统调用获取的是内核的pid值。
3、gettid()代码流程分析
我们从task_pid_vnr()
函数开始分析,这里task_pid_vnr()
调用内部函数__task_pid_nr_ns()
函数,将当前线程的task_struct以及pid_type=PIDTYPE_PID作为参数传入;
static inline pid_t task_pid_vnr(struct task_struct *tsk)
{
return __task_pid_nr_ns(tsk, PIDTYPE_PID, NULL);
}
pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type,
struct pid_namespace *ns)
{
pid_t nr = 0;
rcu_read_lock();
if (!ns) // 由于我们传入到ns指针为NULL,所以需要重新根据当前线程的task_struct获取ns
ns = task_active_pid_ns(current);
// 根据传入pid_type和task_struct指针获取pid指针,再通过pid_nr_ns()从ns中提取到pid值
nr = pid_nr_ns