Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write the program that does the following. Use semaphores . 1. The main (parent)

ID: 3706069 • Letter: W

Question

Write the program that does the following. Use semaphores.

1.       The main (parent) thread initializes an array of  integers to zero.

2.       The parent creates  children. Child  adds 1 to array[], where  = , 1, 2. Order not important.

3.       The parent waits for the children to finish adding, and then prints the values in the array.

4.       The children wait for the parent to finish printing and then repeats (adds 1 to an element of the array)

5.       Continues forever

Pls use c language to answer it!

Explanation / Answer

Raw

sem_server.c

#include <stdio.h> #include <stdlib.h> #include <sys/sem.h> #include <fcntl.h> #include <unistd.h> #include "common.h" int main(int argc, char *argv[]) { int sem_fd; key_t sem_key; int sem_id; int i; struct sembuf sop; // Recover the sem_key from file sem_fd = open(SEM_KEY_FILE, O_RDONLY); if (sem_fd < 0) { perror("Could not open sem key for reading"); exit(1); } // Technically speaking, the read could read less than sizeof(key_t) // Which would be wrong. // But in our case, it is not likely to happen... if (read(sem_fd, &sem_key, sizeof(key_t)) != sizeof(key_t)) { perror("Error reading the semaphore key"); exit(2); } // Done getting the semaphore key close(sem_fd); // Now obtain the (hopefully) existing sem sem_id = semget(sem_key, 0, 0); if (sem_id < 0) { perror("Could not obtain semaphore"); exit(3); } for (i = 0; i < 5; ++i) { sop.sem_num = 0; sop.sem_op = -1; sop.sem_flg = SEM_UNDO; printf("Client #%d waiting ", getpid()); semop(sem_id, &sop, 1); printf("Client #%d acquired. Sleeping ", getpid()); sleep(1); printf("Client #%d releasing ", getpid()); sop.sem_op = 1; semop(sem_id, &sop, 1); } exit(0); }