linux中的pid与tid

1.linux中,每个进程有一个pid,类型pid_t,由getpid()取得。linux下的POSIX线程也有一个id,类型为pthread_t,由pthread_self()取得,该id由线程维护,不同进程中的线程可能有相同的id,每个进程有独立的线程id空间。代码范例:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <pthread.h>
#include <stdlib.h>

void *thread_one()
{
		printf("zi thread_one:int %d main process, the tid=%lu,pid=%ld\n",getpid(),pthread_self(),syscall(SYS_gettid));
}

void *thread_two()
{
		printf("fu thread_two:int %d main process, the tid=%lu,pid=%ld\n",getpid(),pthread_self(),syscall(SYS_gettid));
}

int main(int argc, char *argv[])
{
	pid_t pid;
	pthread_t tid_one, tid_two;
	if((pid = fork()) == -1) {
		perror("fork");
		exit(EXIT_FAILURE);	
	}
	else if(pid == 0) {  	//子进程
		printf("run 2");
		pthread_create(&tid_one, NULL, (void*)thread_one, NULL);
		pthread_join(tid_one, NULL);
	}
	else {								//父进程
		printf("run 1");
		pthread_create(&tid_two, NULL, (void*)thread_two, NULL);
		pthread_join(tid_two, NULL);
		}
	wait(NULL);
	printf("wujinfeng\n");
	return 0;
}
运行结果:
 
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">[root@promote thread]# gcc -o thread thread.c -lpthread
[root@promote thread]# ./thread
run 1fu thread_two:int 19498 main process, the tid=3079285616,pid=19500
run 2zi thread_one:int 19499 main process, the tid=3079285616,pid=19501
wujinfeng
wujinfeng


2.假入有两个进程P1和P2, P1要向另外一个进程P2中的某个线程发送信号,这个时候,既不能使用P2的pid,又不能使用线程的pid,只能使用该线程的真实pid,只能调用syscall来获取线程在内核中的PID即tid(真实id)。  代码范例:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <pthread.h>

struct message
{
	int i;
	int j;
};

void hello(struct message *arg)
{
	printf("child, the pid=%lu, tid=%ld\n", pthread_self(), syscall(SYS_gettid));
	printf("the arg.i is %d, arg.j is %d\n", arg->i, arg->j);	
//	while(1);
}

int main(int argc, char *argv[])
{
	struct message test;
	test.i = 10; 
	test.j = 20;
	pthread_t thread_id;
	
  pthread_create(&thread_id, NULL, (void*)hello, &test);
	printf("parent, the pid=%lu, tid=%ld\n", pthread_self(), syscall(SYS_gettid));
	
	/* 第一个参数为被等待的线程ID, 直到此线程退出。当函数返回时,处于被等待状态的线程资源被收回 */
	pthread_join(thread_id, NULL);	//等待某线程结束
	printf("wujinfeng\n");
}

运行结果:

[root@promote thread]# gcc -o thread thread.c -lpthread
[root@promote thread]# ./thread
parent, the pid=3079358144, tid=19018
child, the pid=3079355248, tid=19019
the arg.i is 10, arg.j is 20
wujinfeng






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值