2024-10-14 11:05:38 +02:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <sys/shm.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
|
|
|
|
#define NUM_PROCS 4
|
|
|
|
#define SHM_SIZE 1024
|
|
|
|
#define PATHNAME "."
|
|
|
|
#define PROJ_ID 65
|
|
|
|
|
|
|
|
int create_mem_segment(int **shm_array) {
|
|
|
|
int shmid;
|
|
|
|
key_t key = ftok(PATHNAME, PROJ_ID);
|
|
|
|
|
|
|
|
// Create a new shared segment
|
|
|
|
if ((shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666)) < 0) {
|
|
|
|
perror("[!] Shmget failed");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Attach (system chooses a suitable address)
|
|
|
|
if ((*shm_array = (int *)shmat(shmid, NULL, 0)) == (int *)-1) {
|
|
|
|
perror("[!] Shmat failed");
|
|
|
|
exit(EXIT_FAILURE);
|
|
|
|
}
|
|
|
|
|
|
|
|
return shmid;
|
|
|
|
}
|
|
|
|
|
|
|
|
int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); }
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
int *shm_array;
|
|
|
|
|
|
|
|
int delay = 5;
|
|
|
|
|
|
|
|
// Creation and attaching into a new shared segment
|
|
|
|
int shmid = create_mem_segment(&shm_array);
|
2024-10-14 11:09:08 +02:00
|
|
|
printf("[SCHEDULER] Shared segment %d created (%p)\n", shmid,
|
|
|
|
(void *)shm_array);
|
2024-10-14 11:05:38 +02:00
|
|
|
|
|
|
|
// Wait until init has finished writing into the segment
|
|
|
|
printf("[SCHEDULER] Sleeping for %d seconds before reading\n", delay);
|
|
|
|
sleep(delay);
|
|
|
|
|
|
|
|
// Copying array to a local variable
|
|
|
|
int priorities[NUM_PROCS];
|
|
|
|
|
|
|
|
for (int i = 0; i < NUM_PROCS; i++) {
|
|
|
|
priorities[i] = shm_array[i];
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: "After scheduler prints the data, init should detach from shared
|
|
|
|
// memory" -> Some mechanism to indicate when init has detached must be put in
|
|
|
|
// place
|
|
|
|
|
|
|
|
// Detaching and deleting the segment
|
|
|
|
shmdt(shm_array);
|
|
|
|
shmctl(shmid, IPC_RMID, NULL);
|
|
|
|
|
|
|
|
// Sorting and printing the priorities
|
|
|
|
qsort(&priorities, NUM_PROCS, sizeof(int), compare);
|
|
|
|
|
|
|
|
printf("[SCHEDULER] Priorities: ");
|
|
|
|
|
|
|
|
for (int i = 0; i < NUM_PROCS; i++) {
|
|
|
|
printf("%d ", priorities[i]);
|
|
|
|
}
|
|
|
|
|
|
|
|
printf("\n");
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|