forked from MuhammeedAlaa/Simplified-OS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clk.c
62 lines (56 loc) · 1.45 KB
/
clk.c
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
/*
* This file is done for you.
* Probably you will not need to change anything.
* This file represents an emulated clock for simulation purpose only.
* It is not a real part of operating system!
*/
#include "headers.h"
int shmid;
int generatorSem;
void up(int sem);
/* Clear the resources before exit */
void cleanup(int signum)
{
shmctl(shmid, IPC_RMID, NULL);
semctl(generatorSem, 0, IPC_RMID, 0);
printf("Clock terminating!\n");
exit(0);
}
/* This file represents the system clock for ease of calculations */
int main(int argc, char *argv[])
{
printf("Clock starting\n");
signal(SIGINT, cleanup);
int clk = 0;
//Create shared memory for one integer variable 4 bytes
shmid = shmget(SHKEY, 4, IPC_CREAT | 0644);
if ((long)shmid == -1)
{
perror("Error in creating shm!");
exit(-1);
}
int *shmaddr = (int *)shmat(shmid, (void *)0, 0);
if ((long)shmaddr == -1)
{
perror("Error in attaching the shm in clock!");
exit(-1);
}
*shmaddr = clk; /* initialize shared memory */
key_t key_id = ftok("keyfile", SEM1KEY);
generatorSem = semget(key_id, 1, 0666 | IPC_CREAT);
while (1)
{
sleep(1);
(*shmaddr)++;
up(generatorSem);
}
}
void up(int sem)
{
union Semun semun;
semun.val = 1;
if (semctl(sem, 0, SETVAL, semun) == -1)
{
perror("error in up");
}
}