溫馨提示×

Linux Getid能獲取線程ID嗎

小樊
82
2024-10-02 07:30:05

在Linux系統(tǒng)中,getpid()函數(shù)用于獲取當(dāng)前進(jìn)程的進(jìn)程ID(PID),而不是線程ID(TID)。要獲取線程ID,應(yīng)使用gettid()函數(shù)。

以下是getpid()gettid()函數(shù)的示例用法:

#include <stdio.h>
#include <unistd.h> // for getpid()
#include <sys/types.h> // for pid_t
#include <sys/syscall.h> // for gettid()

int main() {
    pid_t pid = getpid();
    printf("Current process ID (PID) is: %d\n", pid);

    pid_t tid = syscall(SYS_gettid);
    printf("Current thread ID (TID) is: %d\n", tid);

    return 0;
}

在這個示例中,我們首先使用getpid()函數(shù)獲取當(dāng)前進(jìn)程的PID,然后使用syscall(SYS_gettid)調(diào)用獲取當(dāng)前線程的TID。請注意,SYS_gettid系統(tǒng)調(diào)用是特定于Linux的,可能在其他操作系統(tǒng)上不可用。

0