c/c++ linux 进程间通信系列7,使用pthread mutex

linux 进程间通信系列7,使用pthread mutex

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <pthread.h>
#include <sys/wait.h>

int main(){
  pthread_mutex_t *m;
  pthread_mutexattr_t mat;
  int shmid;
  pid_t pid;

  shmid = shmget(IPC_PRIVATE, sizeof(pthread_mutex_t), 0600);
  if(shmid < 0){
    perror("shmget");
    return 1;
  }

  m = (pthread_mutex_t*)shmat(shmid, NULL, 0);

  //准备设定mutex的attribute
  pthread_mutexattr_init(&mat);

  //利用mutex进行进程间的通信
  //底下这句没有的话,这个mutex只在本进程间有作用
  if(pthread_mutexattr_setpshared(&mat, PTHREAD_PROCESS_SHARED) != 0){
    perror("pthread_mutexattr_setpshared");
    return 1;
  }
  pthread_mutex_init(m, &mat);

  pid = fork();

  printf("[%s] before pthread_mutex_lock()\n",
     pid == 0 ? "child" : "parent");

  if(pthread_mutex_lock(m) != 0){
    perror("pthread_mutex_lock");
    return 1;
  }

  printf("[%s] press enter\n", pid == 0 ? "child" : "parent");
  getchar();

  if(pthread_mutex_unlock(m) != 0){
    perror("pthread_mutex_unlock");
    return 1;
  }

  printf("[%s] after pthread_mutex_lock()\n",
     pid == 0 ? "child" : "parent");

  shmdt(m);

  if(pid != 0){
    wait(NULL);//wait child process to complete
    printf("[%s] after wait()\n", pid == 0 ? "child" : "parent");

    //delete shared memery
    if(shmctl(shmid, IPC_RMID, NULL) != 0){
      perror("shmctl");
      return 1;
    }
  }

  return 0;
}

github源代码

编译方法:

g++ -g process-41-pthread-mutex.cpp -std=c++11 -pthread

运行结果:

[parent] before pthread_mutex_lock()
[parent] press enter
[child] before pthread_mutex_lock()
敲回车
[parent] after pthread_mutex_lock()
[child] press enter
敲回车
[child] after pthread_mutex_lock()
[parent] after wait()

c/c++ 学习互助QQ群:877684253

1414315-20181020224427631-88430648.jpg

本人微信:xiaoshitou5854

转载于:https://www.cnblogs.com/xiaoshiwang/p/9823362.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值