Chinaunix首页 | 论坛 | 博客
  • 博客访问: 391013
  • 博文数量: 87
  • 博客积分: 2571
  • 博客等级: 少校
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-29 13:10
文章分类

全部博文(87)

文章存档

2012年(49)

2011年(7)

2010年(26)

2009年(5)

分类: LINUX

2012-03-28 18:25:19

保存文件名 updatepid.cpp

 编译命令 g++ -lpthread -o pid updatepid.cpp


点击(此处)折叠或打开

  1. #include <stdio.h>

  2. #include <unistd.h>

  3. #include <pthread.h>

  4.  

  5. class Process

  6. {

  7. public:

  8.     pthread_t m_ntid;

  9.     statict int m_nPid;

  10. public:

  11.     Process()

  12.    {

  13.         m_nPid = 0;

  14.         pthread_create(&m_ntid,NULL,mythreadfunc,NULL);

  15.    }

  16.    ~Process(){};

  17.   static void updatePid()

  18.   {

  19.       m_nPid = getpid();

  20.    }

  21.    static void* mythreadfunc(void *arg)

  22.   {

  23.       while(1){

  24.           updatePid();

  25.       }

  26.       return NULL;

  27.   }

  28.  

  29. int Process::m_nPid = -1; //这句很重要(-1这个值无所谓),如果没有,在链接时报Process::m_nPid是undefined reference

  30.  

  31. int main()

  32. {

  33.     Process *p = new Process();

  34.     while(1)

  35.     {

  36.         printf("%d/n",p->m_nPid);

  37.         sleep(1);

  38.     }

  39.     return 0;

  40. }

阅读(747) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~