看ULK3时,说getpid返回的是当前进程的tgid,而不是pid。
对于在一个进程里创建的线程都具有相同的PID,而创建这些线程的进程的pid和tpid的值是相等的。
写了个简单的程序测试下。
- #include<stdio.h>
-
#include<unistd.h>
-
#include<pthread.h>
-
#include<stdlib.h> //exit
-
-
typedef unsigned int uint;
-
-
static void *
-
p1_func(void *arg)
-
{
-
pid_t pid;
-
pthread_t tid;
-
-
pid = getpid();
-
tid = pthread_self();
-
printf("[thread 1]\t\tpid = %u\t tid = %u\n", (uint)pid, (uint)tid);
-
-
return NULL;
-
}
-
-
static void *
-
p2_func(void *arg)
-
{
-
pid_t pid;
-
pthread_t tid;
-
-
pid = getpid();
-
tid = pthread_self();
-
printf("[thread 2]\t\tpid = %u\t tid = %u\n", (uint)pid, (uint)tid);
-
sleep(1);
-
-
return NULL;
-
}
-
-
static void *
-
p3_func(void *arg)
-
{
-
pid_t pid;
-
pthread_t tid;
-
-
pid = getpid();
-
tid = pthread_self();
-
printf("[thread 3]\t\tpid = %u\t tid = %u\n", (uint)pid, (uint)tid);
-
-
return NULL;
-
}
-
-
int main()
-
{
-
pid_t pid, ppid, pid1, pid2;
-
pthread_t tid1, tid2;
-
int err1, err2;
-
-
if ((pid=fork()) < 0){
-
perror("fork error in getpid.c");
-
exit(-1);
-
}
-
else if (pid == 0){ //son
-
ppid = getppid();
-
pid1 = getpid();
-
printf("[son]\t\tppid = %u\t pid = %u\n", (uint)ppid, (uint)pid1);
-
err1 = pthread_create(&tid1, NULL, p1_func, NULL);
-
if (err1 != 0){
-
perror("pthread_create error\n");
-
exit(-1);
-
}
-
}
-
else{ //parent
-
sleep(1);
-
pid2 = getpid();
-
printf("[parent]\t\tpid = %u\n", pid2);
-
err2 = pthread_create(&tid2, NULL, p2_func, NULL);
-
if (err2 != 0){
-
perror("pthread_create error\n");
-
exit(-1);
-
}
-
err2 = pthread_create(&tid2, NULL, p3_func, NULL);
-
if (err2 != 0){
-
perror("pthread_create error\n");
-
exit(-1);
-
}
-
sleep(2);
-
}
-
-
return 0;
-
}
结果:
- [jrq@Fedora LinuxC]$ gcc -o getpid getpid.c -lpthread
-
[jrq@Fedora LinuxC]$ ./getpid
-
[son] ppid = 28178 pid = 28179
-
[thread 1] pid = 28179 tid = 3086056336
-
[parent] pid = 28178
-
[thread 2] pid = 28178 tid = 3086056336
-
[thread 3] pid = 28178 tid = 3075566480
由后三行可知,线程2、3和进程的pid是相同的。他们在一个线程组里。
阅读(1097) | 评论(0) | 转发(0) |