Question: P1.c #include #include #include #include #include #include int main(int argc, char * argv[]) { int fd; int VALUE=1; sem_t *s; //If semaphore with name s

 P1.c #include #include #include #include #include #include int main(int argc, char

P1.c

#include #include #include #include #include #include

int main(int argc, char * argv[]) { int fd; int VALUE=1; sem_t *s; //If semaphore with name "s" does not exist, then create it with VALUE s = sem_open("s", O_CREAT, 0666, VALUE); //can I access the shared file? sem_wait(s); fd=open("data", O_CREAT|O_RDWR|O_APPEND, 0777); write(fd,"P1 prints 1 2 3 4 ",18); close(fd); //semSignal to signal that the shared resource (file) is available sem_post(s); //Before exit, you need to close semaphore and unlink it, when all processes have //finished using the semaphore, it can be removed from the system using sem_unlink sem_close(s); sem_unlink("s"); return 0; }

P2.c

#include #include #include #include #include #include

int main(int argc, char * argv[]) { int fd; int VALUE=1; sem_t *s; s = sem_open("s", O_CREAT, 0666, VALUE); //create the semaphore if it doe snot exist; init to 1 //can I access the shared file? sem_wait(s); fd=open("data", O_CREAT|O_RDWR|O_APPEND, 0777); write(fd,"P2 prints 5 6 7 8 ",18); close(fd); //semSignal to indicate the shared file is available sem_post(s); sem_close(s); sem_unlink("s"); return 0; }

In the next example two processes are sharing a file. Each process checks a shared semaphore s to see if they can access the file. Once access is granted, the process writes to the file, then releases the file. Examine the attached code in P1.c and P2.c. Compile the code using gcc P1.c -pthread gcc P2.C -pthread -O P1 -O P2 Execute with ./P1 & ./P2 and observe the output. Submit a screenshot of the file contents

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!