获取当前进程或线程PID方法

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hello_courage

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值