保存文件名 updatepid.cpp
编译命令 g++ -lpthread -o pid updatepid.cpp
- #include <stdio.h>
- #include <unistd.h>
- #include <pthread.h>
-
- class Process
- {
- public:
- pthread_t m_ntid;
- statict int m_nPid;
- public:
- Process()
- {
- m_nPid = 0;
- pthread_create(&m_ntid,NULL,mythreadfunc,NULL);
- }
- ~Process(){};
- static void updatePid()
- {
- m_nPid = getpid();
- }
- static void* mythreadfunc(void *arg)
- {
- while(1){
- updatePid();
- }
- return NULL;
- }
-
- int Process::m_nPid = -1; //这句很重要(-1这个值无所谓),如果没有,在链接时报Process::m_nPid是undefined reference
-
- int main()
- {
- Process *p = new Process();
- while(1)
- {
- printf("%d/n",p->m_nPid);
- sleep(1);
- }
- return 0;
- }
阅读(803) | 评论(0) | 转发(0) |