linux c获取pid tid的几种方式

获取pid

  • getpid()

获取threadid

  • pthreads API pthread_self()
  • c标准库 thrd_current()
  • linux系统函数 gettid() POSIX thread ID 单线程返回进程号

示例

#define _GNU_SOURCE                                                                                                                              
#include 
#include 
#include 
#include 

#define threadNum 10

void* threadFunc(void* id) 
{
    printf("th %ld tid %lu %lu %d\n",(long)id,pthread_self(), 
            thrd_current()gettid());
    pthread_exit(NULL);
}

int main() {
    pthread_t th[threadNum];
    printf("pid %d\n",getpid());
    for(long i = 0; i < threadNum; i++)
        pthread_create(&th[i],NULL,threadFunc,(void*)i);
    pthread_exit(NULL);
}

你可能感兴趣的:(linux,c语言,运维)