-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dekkers_Using_Fork.c
executable file
·90 lines (78 loc) · 1.81 KB
/
Dekkers_Using_Fork.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/wait.h>
#define N 1
#define M 1000000
typedef struct {
int child_wants_to_enter;
int parent_wants_to_enter;
int turn;
int sharedVar;
} SHARED;
// turn = 0 -> child
// turn = 1 -> parent
SHARED * smp;
void child(){
smp->child_wants_to_enter = 1;
while(smp->parent_wants_to_enter){
if(smp->turn){
smp->child_wants_to_enter = 0;
while(smp->turn)
;
}
}
smp->sharedVar += 1;
// printf("Child Process : %d\n", smp->sharedVar);
smp->child_wants_to_enter = 0;
smp->turn = 1;
}
void parent(){
smp->parent_wants_to_enter = 1;
while(smp->child_wants_to_enter){
if(!smp->turn){
smp->parent_wants_to_enter = 0;
while(!smp->turn)
;
}
}
smp->sharedVar += 1;
// printf("Parent Process : %d\n", smp->sharedVar);
smp->parent_wants_to_enter = 0;
smp->turn = 0;
}
int main(){
int shmid = shmget(1234, sizeof(SHARED), IPC_CREAT | 0777);
if(shmid < 0){
perror("Failed TO Get Shared Memory\n");
exit(0);
}
smp = shmat(shmid, (void*)0, 0);
if(smp == (void*)-1){
perror("Shared Memory Attach Failed\n");
exit(0);
}
smp->child_wants_to_enter = 0;
smp->parent_wants_to_enter = 0;
smp->turn = 0;
smp->sharedVar = 0;
printf("Initial Value : %d\n", smp->sharedVar);
int rc = fork();
if(-1 == rc){
printf("Fork Failed\n");
exit(0);
}
for(int i = 0; i < M; i++){
if(0 == rc){
child();
} else if(rc > 0){
parent();
wait(NULL);
}
}
printf("Final Value : %d\n", smp->sharedVar);
return 0;
}