- 论坛徽章:
- 36
|
本帖最后由 cokeboL 于 2011-06-20 17:43 编辑
3楼说得对
jitashan 发表于 2011-06-20 16:16 ![]()
线程和进程的pid不同,分别为parent和子进程的pid,getpid()调用比较。设置个全局的pid_flag = getpid(),然后线程和子进程中if比较。- /* test.c */
- #include <stdio.h>
- #include <pthread.h>
- pid_t pid_flag;
- void *func(void *);
- int main()
- {
- pthread_t tid;
- pid_t pid;
- printf("parent's pid: %d\n", pid_flag=getpid());
- pthread_create(&tid, 0, func, 0);
- pthread_join(tid, 0);
- if( (pid=fork()) == 0 ) {
- if(pid_flag == getpid())
- printf("Child pid(%d) == parent pid\n", getpid());
- else
- printf("Child pid(%d) != parent pid\n", getpid());
- }
- }
- void *func(void *s)
- {
- if(pid_flag == getpid())
- printf("Thread pid(%d) == parent pid\n", getpid());
- }
复制代码- [cokeboL@localhost ~]$ cc test.c -lpthread
- [cokeboL@localhost ~]$ a.out
- parent's pid: 24880
- Thread pid(24880) == parent pid
- Child pid(24882) != parent pid
复制代码 |
|