-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExample03-sem.c
More file actions
83 lines (79 loc) · 1.79 KB
/
Copy pathExample03-sem.c
File metadata and controls
83 lines (79 loc) · 1.79 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define KEY 0x1111 //to refer to same IPC structure
union semun
{
int val;
struct semid_ds* buf;
unsigned short* array;
};
struct sembuf p = {0, -1, SEM_UNDO}; //semWait
struct sembuf v = {0, +1, SEM_UNDO}; //semSignal
int main(){
int id = semget(KEY,1,0666 | IPC_CREAT);
if(id < 0){
perror("semget");
exit(11);
}
union semun u;
u.val = 1;
if(semctl(id,0,SETVAL,u) < 0){
perror("semctl");
exit(12);
}
int pid;
pid = fork();
srand(pid);
if(pid < 0){
perror("pid");
exit(1);
}else if(pid){
char *s = "abcdefgh";
int l = strlen(s);
for (int i = 0; i < l; ++i){
if(semop(id,&p,1) < 0){
perror("semop p");
exit(13);
}
putchar(s[i]);
fflush(stdout);
sleep(rand() % 2);
putchar(s[i]);
fflush(stdout);
if (semop(id, &v, 1) < 0)
{
perror("semop v");
exit(14);
}
sleep(rand() % 2);
}
}else{
char *s = "ABCDEFGH";
int l = strlen(s);
for (int i = 0; i < l; ++i)
{
if (semop(id, &p, 1) < 0)
{
perror("semop p");
exit(15);
}
putchar(s[i]);
fflush(stdout);
sleep(rand() % 2);
putchar(s[i]);
fflush(stdout);
if (semop(id, &v, 1) < 0)
{
perror("semop v");
exit(16);
}
sleep(rand() % 2);
}
}
return 0;
}