1. 程式人生 > >c/c++ linux 進程間通信系列7,使用pthread mutex

c/c++ linux 進程間通信系列7,使用pthread mutex

shm delete clu wait 進程間通信 pro -m printf gre

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

技術分享圖片

本人微信:xiaoshitou5854

c/c++ linux 進程間通信系列7,使用pthread mutex