forked from yuebaixiao/network
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess-41-pthread-mutex.cpp
68 lines (53 loc) · 1.4 KB
/
process-41-pthread-mutex.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#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;
}