Skip to content

Commit e54a1ab

Browse files
authored
Add files via upload
1 parent d64b77c commit e54a1ab

File tree

4 files changed

+88
-0
lines changed

4 files changed

+88
-0
lines changed

Semaphore/bin/semaphore

20.7 KB
Binary file not shown.

Semaphore/inc/main.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
#include <stdio.h>
2+
#include <sys/types.h>
3+
#include <sys/ipc.h>
4+
#include <sys/sem.h>
5+
#include <stdlib.h>
6+
#include <unistd.h>
7+
#include <string.h>

Semaphore/obj/main.o

10.6 KB
Binary file not shown.

Semaphore/src/main.c

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#include "main.h"
2+
3+
#define KEY 0x1111
4+
5+
union semun {
6+
int value;
7+
struct semid_ds *buf;
8+
unsigned short *arr;
9+
};
10+
11+
struct sembuf a = {0, -1, SEM_UNDO};
12+
struct sembuf b = {0, +1, SEM_UNDO};
13+
14+
int main(void)
15+
{
16+
int id = semget(KEY, 1, 0666 | IPC_CREAT);
17+
if (id < 0) {
18+
perror("semget\n");
19+
exit(0);
20+
}
21+
union semun su;
22+
su.value = 1;
23+
24+
if(semctl(id, 0, SETVAL, su) < 0) {
25+
perror("semctl error");
26+
exit(0);
27+
}
28+
29+
int pid;
30+
31+
pid = fork();
32+
srand(pid);
33+
34+
if (pid < 0) {
35+
perror("fork error\n");
36+
exit(0);
37+
} else if (pid) {
38+
char *se = "abc";
39+
int l = strlen(se);
40+
41+
for (int i = 0; i < l; i++) {
42+
if (semop(id, &a, 1) < 0) {
43+
perror("semop error with a\n");
44+
exit(0);
45+
}
46+
putchar(se[i]);
47+
fflush(stdout);
48+
sleep(1);
49+
putchar(se[i]);
50+
fflush(stdout);
51+
if (semop(id, &b, 1) < 0) {
52+
perror("semop error with b\n");
53+
exit(0);
54+
}
55+
56+
sleep(1);
57+
}
58+
} else {
59+
char *se = "abc";
60+
int l = strlen(se);
61+
62+
for (int i = 0; i < l; i++) {
63+
if (semop(id, &a, 1) < 0) {
64+
perror("semop error with a\n");
65+
exit(0);
66+
}
67+
putchar(se[i]);
68+
fflush(stdout);
69+
sleep(1);
70+
putchar(se[i]);
71+
fflush(stdout);
72+
if (semop(id, &b, 1) < 0) {
73+
perror("semop error with b\n");
74+
exit(0);
75+
}
76+
77+
sleep(1);
78+
}
79+
}
80+
return 0;
81+
}

0 commit comments

Comments
 (0)