#include #include #include #include #define NUM_PROCS 4 #define SHM_SIZE 1024 #define PATHNAME "." #define PROJ_ID 65 struct shared_data { int ready; int priorities[NUM_PROCS]; }; int create_mem_segment(struct shared_data **shm_ptr) { int shmid; key_t key = ftok(PATHNAME, PROJ_ID); printf("[SCHEDULER] Shared segment key: %d\n", key); // 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_ptr = (struct shared_data *)shmat(shmid, NULL, 0)) == (struct shared_data *)-1) { perror("[!] Shmat failed"); exit(EXIT_FAILURE); } return shmid; } int compare(const void *a, const void *b) { return (*(int *)a - *(int *)b); } int main() { struct shared_data *shm_ptr; // Create and attach into a new shared segment int shmid = create_mem_segment(&shm_ptr); printf("[SCHEDULER] Shared segment %d created (%p)\n", shmid, (void *)shm_ptr); // Initialize signal flag to 0 (not ready) shm_ptr->ready = 0; printf("[SCHEDULER] Signal flag initialized to 0\n"); printf("[SCHEDULER] Waiting for init to write data...\n"); // Wait until init has finished writing into the segment while (shm_ptr->ready == 0) { usleep(100000); // 100 ms (to reduce CPU usage) } int priorities[NUM_PROCS]; // Copy array to a local variable for (int i = 0; i < NUM_PROCS; i++) { priorities[i] = shm_ptr->priorities[i]; } // Detach if (shmdt(shm_ptr) == -1) { perror("[!] Shmdt failed"); exit(EXIT_FAILURE); } // Delete if (shmctl(shmid, IPC_RMID, NULL) == -1) { perror("[!] Shmctl failed"); exit(EXIT_FAILURE); } printf("[SCHEDULER] Shared memory segment %d detached and deleted\n", shmid); printf("[SCHEDULER] Unsorted priorities: "); // Print the priorities before sorting (for comparison) for (int i = 0; i < NUM_PROCS; i++) { printf("%d ", priorities[i]); } printf("\n"); // Sort and print the priorities qsort(&priorities, NUM_PROCS, sizeof(int), compare); printf("[SCHEDULER] Sorted priorities: "); for (int i = 0; i < NUM_PROCS; i++) { printf("%d ", priorities[i]); } printf("\n"); printf("[SCHEDULER] Exiting...\n"); return 0; }