-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkomisja.c
84 lines (71 loc) · 2.49 KB
/
komisja.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
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <signal.h>
#include "const.h"
#include "error.h"
#include "./headers/sharedMemory.h"
#include "./headers/semaphore.h"
void setupKomisje(char* type, char* numberOfStudents, int* memoryBlock);
int semID;
// Signal handler to set the flag when a signal is received
void signalHandler(int sig) {
if (sig == SIGUSR2) {
destroyMemoryBlock(shm_KOMISJA);
destroySemaphore(semID, 0);
}
}
int main(int argc, char* argv[]) {
(void)argc;
// Set up the signal for the Dziekan to terminate the Komisja when it has finished.
if (signal(SIGUSR1, signalHandler) == SIG_ERR) {
perror(errors[SIGNAL_HANDLER]);
}
// Set up the signal for the Dziekan to terminate the Komisja when there is a fire.
if (signal(SIGUSR2, signalHandler) == SIG_ERR) {
perror(errors[SIGNAL_HANDLER]);
}
semID = allocSemaphore(sem_KOMISJA, 1, IPC_CREAT | 0666);
initSemaphore(semID, 0, 0);
// Create the shared memory with the Dziekanat so that you can pass the pid of KomisjaA and KomisjaB.
int* memoryBlock = (int*)attachMemoryBlock(shm_KOMISJA, shm_KOMISJA_SIZE);
if (memoryBlock == NULL) {
printf(errors[SHARED_MEMORY]);
return -1;
}
setupKomisje("A", argv[1], memoryBlock);
setupKomisje("B", argv[1], memoryBlock + 1);
signalSemaphore(semID, 0, 1);
printf("A pid: %d, B pid: %d \n", *memoryBlock, *(memoryBlock + 1));
wait(NULL);
wait(NULL);
destroySemaphore(semID, 0);
destroyMemoryBlock(shm_KOMISJA);
return 0;
}
void setupKomisje(char* type, char* numberOfStudents, int* memoryBlock) {
// Allocate the needed memory so that I can save the pid of the parent, that is Dziekan.c
char* ppid = malloc(sizeof(char) * 10);
if (ppid == NULL) { // Error handling.
perror(errors[MEMORY_ALLOCATION]);
}
sprintf(ppid, "%d", getppid());
// Save the pid in the variable so that it could be saved in the shared memory by the Parent.
int newPID = fork();
switch (newPID) {
case -1:
perror(errors[FORK]);
break;
case 0:
// Get the number of only the selected student that are going to take the Egzam.
execlp("./komisjaT", "./komisjaT", type, numberOfStudents, ppid, NULL);
break;
default:
// Save the new child PID.
*memoryBlock = newPID;
break;
}
}