forked from naelag/lab2-f17
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shm_cnt.c
48 lines (40 loc) · 1.23 KB
/
shm_cnt.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
#include "types.h"
#include "stat.h"
#include "user.h"
#include "uspinlock.h"
struct shm_cnt {
struct uspinlock lock;
int cnt;
};
int main(int argc, char *argv[])
{
int pid;
int i=0;
struct shm_cnt *counter;
pid=fork();
sleep(1);
//shm_open: first process will create the page, the second will just attach to the same page
//we get the virtual address of the page returned into counter
//which we can now use but will be shared between the two processes
shm_open(1,(char **)&counter);
// printf(1,"%s returned successfully from shm_open with counter %x\n", pid? "Child": "Parent", counter);
for(i = 0; i < 10000; i++)
{
uacquire(&(counter->lock));
counter->cnt++;
urelease(&(counter->lock));
//print something because we are curious and to give a chance to switch process
if(i%1000 == 0)
printf(1,"Counter in %s is %d at address %x\n",pid? "Parent" : "Child", counter->cnt, counter);
}
if(pid)
{
printf(1,"Counter in parent is %d\n",counter->cnt);
wait();
} else
printf(1,"Counter in child is %d\n\n",counter->cnt);
//shm_close: first process will just detach, next one will free up the shm_table entry (but for now not the page)
shm_close(1);
exit();
return 0;
}