Linux系统函数getpid获取的是进程描述符task_struct的tgid(thread group identifier),而pid(process identifier)是系统管理所有进程的id。

测试代码:

#include <stdio.h>

#include <pthread.h>

int *thread(void *arg)
{
printf("thread pid = %d\n",(int)getpid());
sleep(100);
return NULL; 
}

int main(void)
{
pthread_t thid;
pthread_create(&thid,NULL,(void *)thread,NULL);
printf("main thread pid = %d\n",(int)getpid());
sleep(110); 
return 0; 

}

运行:

/tmp # ./getpid &
main thread pid = 677 
thread pid = 677               ===>>证明getpid其实就是获取tgid,主线程和子线程都是一样的,但是pid不一样

 

/tmp # ps -T
PID   USER     TIME   COMMAND
    1 0          0:01 init
    2 0          0:00 [kthreadd]
    3 0          0:00 [ksoftirqd/0]
    5 0          0:42 [kworker/u:0]
    6 0          0:00 [migration/0]
    7 0          0:00 [khelper]
    8 0          0:00 [kworker/u:1]
  199 0          0:00 [sync_supers]
  201 0          0:00 [bdi-default]
  203 0          0:00 [kblockd]
  229 0          0:00 [imx6q-ecspi.0]
  232 0          0:00 [imx6q-ecspi.2]
  243 0          0:00 [khubd]
  339 0          0:00 [rpciod]
  340 0          0:00 [kworker/0:1]
  347 0          0:00 [usb_wakeup thre]
  349 0          0:00 [usb_wakeup thre]
  361 0          0:00 [kswapd0]
  362 0          0:00 [ksmd]
  363 0          0:00 [fsnotify_mark]
  364 0          0:00 [nfsiod]
  369 0          0:00 [crypto]
  378 0          0:39 [throbber]
  539 0          0:00 [kworker/u:3]
  550 0          0:00 [mmcqd/0]
  551 0          0:00 [mmcqd/0boot0]
  552 0          0:00 [mmcqd/0boot1]
  595 0          0:00 [migration/1]
  596 0          0:00 [kworker/1:0]
  597 0          0:00 [ksoftirqd/1]
  600 0          0:00 [migration/2]
  601 0          0:00 [kworker/2:0]
  602 0          0:00 [ksoftirqd/2]
  605 0          0:00 [migration/3]
  606 0          0:00 [kworker/3:0]
  607 0          0:00 [ksoftirqd/3]
  609 0          0:00 /bin/sh
  610 0          0:00 [kworker/2:1]
  643 0          0:00 [kworker/1:1]
  655 0          0:00 [kworker/0:0]
  656 0          0:00 [kworker/0:2]
  668 0          0:00 [kworker/3:1]
  677 0          0:00 ./getpid            //主线程pid为677,tgid为677,此线程为线程组的第一个进程
  678 0          0:00 ./getpid            //子线程pid为678,tgid为677,子线程的tgid为线程组的第一个进程
  680 0          0:00 ps -T
/tmp # 

另外:

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/syscall.h>  
#define gettid() syscall(__NR_gettid)   //获取线程ID
int *thread(void *arg)
{
printf("thread pid = %d\n",(int)getpid());
printf("thread tid = %d\n",(int)gettid());
sleep(100);
return NULL; 
}
int main(void)
{
pthread_t thid;
pthread_create(&thid,NULL,(void *)thread,NULL);
printf("main thread pid = %d\n",(int)getpid());
printf("main thread tid = %d\n",(int)gettid());
sleep(110); 
return 0; 
}

Logo

更多推荐