日期:2014-05-16  浏览次数:20574 次

linux多线程在/proc目录的结构

linux的多线程,其实就是clone系统调用的实现的(共享文件等)

首先看个具体的例子:

#include <stdio.h>  
#include <stdlib.h>  
#include <pthread.h>  
#include <unistd.h>
#include <string.h>
#include <sched.h>
#include <errno.h>
  
void *print_message_function( void *ptr );  

int main()  
{  

      pthread_t thread1, thread2;  
      const char *message1 = "Thread 1";  
      const char *message2 = "Thread 2";  
      int  iret1, iret2;  
   
     /* Create independent threads each of which will execute function */ 
      iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);  
      iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);  

      /* Wait till threads are complete before main continues. Unless we  */ 
      /* wait we run the risk of executing an exit which will terminate   */ 
      /* the process and all threads before the threads have completed.   */     

      pthread_join( thread1, NULL);  
      pthread_join( thread2, NULL);       
      printf("Thread 1 returns: %d\n",iret1);  
      printf("Thread 2 returns: %d\n",iret2);  
      for(;;)
      {
         usleep(250*1000);
      } 
      return 0;
      
}      
void *print_message_function( void *ptr )  
{  
      char *message;  
      for(;;)
      {
         message = (char *) ptr;  
         printf("%s \n", message);
         usleep(3*250*1000);
      }  
      return 0;
} 


此时一共有三个进程在跑(相对于kernel来说,只有进程的概念)

一般情况是,一个进程在/proc 目录下就对应一个,以该进程ID号名字的

文件目录,该目录下保存着该进程的所有信息。

但是对应,所谓的多线程,它的目录结构该会这么样呢?

假如该程序名为:thread

$ top  -t  | grep thread
PID      TID PR CPU% S     VSS     RSS PCY UID      Thread          Proc

31694 31694  0   0% S   3008K    416K     root     thread          system/bin/thread
31694 31695  0   0% S   3008K    416K     root     thread          system/bin/thread
31694 31696  0   0% S   3008K    416K     root     thread          system/bin/thread

可知他们对应于一个进程ID号,而在此目录下,分别在有其他三个线程目录信息:

proc/31694/task # ls
31694
31695
31696