1. #include    <stdio.h>  
  2. #include    <stdlib.h>  
  3. #include    <unistd.h>  
  4. #include    <fcntl.h>  
  5. #include    <sys/mman.h>  
  6. #include    <pthread.h>  
  7. pthread_mutex_t* g_mutex;  
  8. //创建共享的mutex  
  9. void init_mutex(void)  
  10. {  
  11.     int ret;  
  12.     //g_mutex一定要是进程间可以共享的,否则无法达到进程间互斥  
  13.     g_mutex=(pthread_mutex_t*)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);  
  14.     if( MAP_FAILED==g_mutex )  //使用匿名存储映射,只能在具有亲缘关系的进程间使用,
  15.     {                                      //若要在非亲缘关系进程间使用需要mmap文件映射结合SHARED                                             //标志或者共享内存IPC
  16.         perror("mmap");  
  17.         exit(1);  
  18.     }  
  19.       
  20.     //设置attr的属性  
  21.     pthread_mutexattr_t attr;  
  22.     pthread_mutexattr_init(&attr);  
  23.     //一定要设置为PTHREAD_PROCESS_SHARED  
  24.     //具体可以参考http://blog.chinaunix.net/u/22935/showart_340408.html  
  25.     ret=pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);  
  26.     if( ret!=0 )  
  27.     {  
  28.         perror("init_mutex pthread_mutexattr_setpshared");  
  29.         exit(1);  
  30.     }  
  31.     pthread_mutex_init(g_mutex, &attr);  
  32. }  
  33. int main(int argc, char *argv[])  
  34. {  
  35.     init_mutex();  
  36.     int ret;      
  37.     char str1[]="this is child process/r/n";  
  38.     char str2[]="this is father process/r/n";  
  39.     int fd=open("tmp", O_RDWR|O_CREAT|O_TRUNC, 0666);  
  40.     if( -1==fd )  
  41.     {  
  42.         perror("open");  
  43.         exit(1);  
  44.     }  
  45.     pid_t pid;  
  46.     pid=fork();  
  47.     if( pid<0 )  
  48.     {  
  49.         perror("fork");  
  50.         exit(1);  
  51.     }  
  52.     else if( 0==pid )  
  53.     {  
  54.         ret=pthread_mutex_lock(g_mutex);  
  55.         if( ret!=0 )  
  56.         {  
  57.             perror("child pthread_mutex_lock");  
  58.         }  
  59.         sleep(10);//测试是否能够阻止父进程的写入  
  60.         write(fd, str1, sizeof(str1));  
  61.         ret=pthread_mutex_unlock(g_mutex);    
  62.         if( ret!=0 )  
  63.         {  
  64.             perror("child pthread_mutex_unlock");  
  65.         }     
  66.     }  
  67.     else  
  68.     {  
  69.         sleep(2);//保证子进程先执行   
  70.         ret=pthread_mutex_lock(g_mutex);  
  71.         if( ret!=0 )  
  72.         {  
  73.             perror("father pthread_mutex_lock");  
  74.         }  
  75.         write(fd, str2, sizeof(str2));  
  76.         ret=pthread_mutex_unlock(g_mutex);    
  77.         if( ret!=0 )  
  78.         {  
  79.             perror("father pthread_mutex_unlock");  
  80.         }                 
  81.     }  
  82.     wait(NULL);  
  83.     munmap(g_mutex, sizeof(pthread_mutex_t));  
  84. }  

运行后tmp文件内容为:

this is child process

this is father process


Logo

更多推荐