Summary Files Commits Branches @commit @diff @stats
path: root / Year 3 / System programming / Practice10 / ex3.c
blob: 0580a38b3faf6775eb77009443e3f1d7ec966540 (plain) (blame)
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
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
	int shmd = shm_open("/shm", O_RDWR | O_TRUNC | O_CREAT, 0755);
	ftruncate(shmd, sizeof(int));
	int* memory = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_SHARED, shmd, 0);

	*memory = 0;

	int fod = fork();
	if (fod == 0) {
		while (*memory < 100) {
			*memory += 1;
			printf("%d %d\n", getpid(), *memory);
			sleep(1);
		}
	}
	else {
		while (*memory < 100) {
			sleep(2);
			*memory += 1;
			printf("%d %d\n", getpid(), *memory);
		}
	}

	munmap(memory, sizeof(int));
	close(shmd);
	if (fod != 0)
		shm_unlink("/shm");

	return 0;
}