PID vs TID in Linux
PID Stands for Process ID and TID stands for Thread ID.
Each process in Linux Kernel is internally represented by task_struct (present in include/linux/sched.h)
To get the process ID, we call getpid() API in Linux and gettid() for thread ID.
Let's see what happens internally when we call this API.
From the screenshot, we can see that kernel returns pid member of the task_struct structure when we call gettid() and tgid member of the task_struct when we call getpid()
tgid -> Thread Group ID.
Difference between pid and tgid:
Linux implements all threads as standard processes, Each thread will have an unique task_struct and appears to kernel as normal process, and share resources such as address space, open files etc with other processes.
The pid field in the task_struct is used to identify the thread of the process , and tgid is used to identify the pid of the thread which started the process
When a new process is created, the value of both tgid and pid will be same, only when a new thread is created in the code, pid of that thread will change but tgid will be same.
Code:
Output:
Each process in Linux Kernel is internally represented by task_struct (present in include/linux/sched.h)
To get the process ID, we call getpid() API in Linux and gettid() for thread ID.
Let's see what happens internally when we call this API.
From the screenshot, we can see that kernel returns pid member of the task_struct structure when we call gettid() and tgid member of the task_struct when we call getpid()
tgid -> Thread Group ID.
Difference between pid and tgid:
Linux implements all threads as standard processes, Each thread will have an unique task_struct and appears to kernel as normal process, and share resources such as address space, open files etc with other processes.
The pid field in the task_struct is used to identify the thread of the process , and tgid is used to identify the pid of the thread which started the process
When a new process is created, the value of both tgid and pid will be same, only when a new thread is created in the code, pid of that thread will change but tgid will be same.
Code:
Output:
Notes:
1. man gettid tells you that "GLibc does not provide you a wrapper for this system call". So, we use syscall for calling gettid
I'll try it on Termux!
ReplyDelete