A text file named \"common.txt\" allows N concurrent processes to read and write
ID: 3638992 • Letter: A
Question
A text file named "common.txt" allows N concurrent processes to read and write to it. However, only one process can access a file at a time. At the beginning of the file is a counter. When a process accesses the file, it first reads the counter, increments its value by one, updates it and append a message like the following to the file:I am process process_id who have visited you!
The process then closes the file and sleeps for a random amount of time between 0 to 3 seconds. If the file does not exist, the first process which tries to access it will create the file and set the counter to 0.
Make use of a POSIX semaphore to implement these capabilities and test your program with at least 2 processes. The following is sample content of the file "common.txt":
8
I am process 1 who have visited you!
I am process 2 who have visited you!
I am process 1 who have visited you!
I am process 1 who have visited you!
I am process 3 who have visited you!
I am process 2 who have visited you!
I am process 3 who have visited you!
...........
Explanation / Answer
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define P(s) semop(s, &pop, 1) /* pop is the structure we pass for doing
the P(s) operation */
#define V(s) semop(s, &vop, 1) /* vop is the structure we pass for doing
the V(s) operation */
int main()
{
semid1 = semget(ftok("/usr/lib",1), 1, 0777|IPC_CREAT|IPC_EXCL);
int i;
char j;
if(semid1 < 0)
{
semid1 = semget(ftok("/usr/lib",1), 1, 0777|IPC_CREAT);
}
else
{
semctl(semid1, 0, SETVAL, 0);
}
pop.sem_num = vop.sem_num = 0;
pop.sem_flg = vop.sem_flg = 0;
pop.sem_op = -1 ; vop.sem_op = 1 ;
P(semid1);
FILE * fp = fopen("common.txt","ar+");
fscanf(fp,"%d",&i);
i++;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.