-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask4.c
More file actions
78 lines (63 loc) · 1.67 KB
/
task4.c
File metadata and controls
78 lines (63 loc) · 1.67 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
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#define SHM_KEY 9979
int main(void) {
// n -> Process counter, m = loops each process
const int n = 1000, m = 10000;
int pid, shmid, semid, RESULT_FIFO;
char *fifo = "/tmp/RESULT_FIFO";
sem_t mutex;
// get SEM
semid = sem_init(&mutex, 0, 1);
if (semid < 0) {
perror("sem_init");
exit(EXIT_FAILURE);
}
// Get SHM
shmid = shmget(SHM_KEY, 0, 0660);
if (shmid < 0) {
perror("shmget");
exit(EXIT_FAILURE);
}
int *data = (int *)shmat(shmid, NULL, 0); // SHM_WRONLY
if (*data == -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
// Creates n Processes
for (int i = 1; i <= n; i++) {
// Create fork
pid = fork();
if (pid == 0) {
for (int i = 1; i <= m; i++) {
/* Join critical area */
sem_wait(&mutex);
// Inc val in SHM
*data = *data + 1;
/* Leave critical area */
sem_post(&mutex);
}
exit(EXIT_SUCCESS);
}
}
// Wait for Child
for (int i = 1; i <= n; i++) waitpid(pid, NULL, 0);
// Read from SHM > stdout
fprintf(stdout, "Data: %d\n", *data);
// Write to RESULT_FIFO
RESULT_FIFO = open(fifo, O_WRONLY);
if (RESULT_FIFO != -1) write(RESULT_FIFO, data, sizeof(data));
// destroy mutex
sem_destroy(&mutex);
// close fifo
close(RESULT_FIFO);
return EXIT_SUCCESS;
}