PID,进程ID
PPID,父进程ID
TID( LWP),线程ID
1. 用户态获取进程ID
1.1进程ID
getpid, getppid - get process identification
#include <unistd.h>
pid_t getpid(void); // 获取当前进程的PID
pid_t getppid(void); // 获取当前进程的PPID
getpid() returns the process ID (PID) of the calling process.
(This is often used by routines that generate unique temporary
filenames.)
getppid() returns the process ID of the parent of the calling
process.
1.2 线程ID:
1) gettid
get thread identification
#define _GNU_SOURCE
#include <unistd.h>
pid_t gettid(void);
gettid() returns the caller's thread ID (TID). In a single-
threaded process, the thread ID is equal to the process ID (PID,
as returned by getpid(2)). In a multithreaded process, all
threads have the same PID, but each one has a unique TID.
2) pthread_self
#include <pthread.h>
TaskID = (pthread_t)(pthread_self());
pthread_t由pthread线程库分配和维护,仅能保证同一个进程中是唯一的。但POSIX标准并没有规定pthread_t的具体格式,不同系统中pthread_t的实现可能是不一样的。
3)区别
pthread_self返回的是同一个进程中各个线程之间的标识号,对于这个进程内是唯一的,而不同进程中,每个线程返回的pthread_self可能是一样的。而gettid是整个系统内各个线程间的标识符,由于linux采用轻量级进程实现的,它其实返回是pid号。
2. 内核态获取进程ID
1)变量方法:
current->pid;,线程ID
current->tgid;,进程ID
current 不需要额外声明定义;内核变量;
2)函数方法:
sys_getpid,进程ID
sys_gettid,线程ID