-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path031b.c
More file actions
81 lines (63 loc) · 2.25 KB
/
031b.c
File metadata and controls
81 lines (63 loc) · 2.25 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
/*
..........................................................................................................................................
Name : 031b.c
Author : SHRUTI VERMA
Description : Write a program to create a semaphore and initialize value to the semaphore.
a. create a binary semaphore
b. create a counting semaphore
Date : 16 Sep 2025
..........................................................................................................................................
*/
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<semaphore.h>
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
struct seminfo *__buf;
};
int main() {
int key, semid;
union semun u;
struct sembuf lock = {0, -1, SEM_UNDO};
struct sembuf unlock = {0, 1, SEM_UNDO};
key = ftok("file.txt",65);
semid = semget(key, 1, IPC_CREAT | IPC_EXCL | 0666);
printf("waiting to enter critical section\n");
if(semid>=0) {
u.val = 3;
semctl(semid, 0, SETVAL, u);
} else semid = semget(key, 1, 0666);
semop(semid, &lock, 1);
printf("%d in critical section\n", getpid());
printf("releasing counting semaphore : press enter\n");
getchar();
semop(semid, &unlock, 1);
printf("counting semaphore released\n");
}
/*------------------------------------OUTPUT----------------------------------------------
terminal 1
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ gcc 031b.c -o 031b.out
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ ./031b.out
waiting to enter critical section
22776 in critical section
releasing counting semaphore : press enter
terminal 2
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ ./031b.out
waiting to enter critical section
22817 in critical section
releasing counting semaphore : press enter
terminal 3
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ ./031b.out
waiting to enter critical section
22808 in critical section
releasing counting semaphore : press enter
terminal 4
vumma@vumma-VivoBook-15-ASUS-Laptop-X507UF:~/Desktop/SS/HOL2$ ./031b.out
waiting to enter critical section
*/