Linux下的多进程间共享资源的互斥访问

               
#include    <stdio.h>  #include    <stdlib.h>  #include    <unistd.h>  #include    <fcntl.h>  #include    <sys/mman.h>  #include    <pthread.h>  pthread_mutex_t* g_mutex;  //创建共享的mutex  void init_mutex(void)  {      int ret;      //g_mutex一定要是进程间可以共享的,否则无法达到进程间互斥      g_mutex=(pthread_mutex_t*)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);      if( MAP_FAILED==g_mutex )      {          perror("mmap");          exit(1);      }            //设置attr的属性      pthread_mutexattr_t attr;      pthread_mutexattr_init(&attr);      //一定要设置为PTHREAD_PROCESS_SHARED      //具体可以参考http://blog.chinaunix.net/u/22935/showart_340408.html      ret=pthread_mutexattr_setpshared(&attr,PTHREAD_PROCESS_SHARED);      if( ret!=0 )      {          perror("init_mutex pthread_mutexattr_setpshared");          exit(1);      }      pthread_mutex_init(g_mutex, &attr);  }  int main(int argc, char *argv[])  {      init_mutex();      int ret;          char str1[]="this is child process/r/n";      char str2[]="this is father process/r/n";      int fd=open("tmp", O_RDWR|O_CREAT|O_TRUNC, 0666);      if( -1==fd )      {          perror("open");          exit(1);      }      pid_t pid;      pid=fork();      if( pid<0 )      {          perror("fork");          exit(1);      }      else if( 0==pid )      {          ret=pthread_mutex_lock(g_mutex);          if( ret!=0 )          {              perror("child pthread_mutex_lock");          }          sleep(10);//测试是否能够阻止父进程的写入          write(fd, str1, sizeof(str1));          ret=pthread_mutex_unlock(g_mutex);            if( ret!=0 )          {              perror("child pthread_mutex_unlock");          }         }      else      {          sleep(2);//保证子进程先执行           ret=pthread_mutex_lock(g_mutex);          if( ret!=0 )          {              perror("father pthread_mutex_lock");          }          write(fd, str2, sizeof(str2));          ret=pthread_mutex_unlock(g_mutex);            if( ret!=0 )          {              perror("father pthread_mutex_unlock");          }                     }      wait(NULL);      munmap(g_mutex, sizeof(pthread_mutex_t));  }  


运行后tmp文件内容为:

this is child process

this is father process



           
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值