I have 2 programs that need to communicate with each other, the first one must output what the second one puts into the shared memory, but I've removed everything but the semaphores, because there is a problem with synchronization. This is a school assignment, so I must use semaphores in exactly the way shown below, don't propse anything else because I can't use it.
#include <sys/shm.h>
#include <errno.h>
#include <sys/sem.h>
int main()
{
int semid;
struct sembuf sobs;
semid=semget(9999,1,IPC_CREAT|0600);
semctl(semid, 0, SETVAL,1);
sobs.sem_num=0;
sobs.sem_op= 0;
sobs.sem_flg=0;
semop(semid,&sobs,1);
/* DO SOMETHING */
sobs.sem_op=1;
semop(semid,&sobs,1);
shmctl(shmid1,IPC_RMID,0);
return 0;
}
And the second program:
#include <sys/shm.h>
#include <errno.h>
#include <sys/sem.h>
int main()
{
int semid;
struct sembuf sobs;
semid=semget(9999,1,0600);
sobs.sem_num=0;
sobs.sem_op=-1;
sobs.sem_flg=0;
semop(semid,&sobs,1);
/* DO SOMETHING */
sobs.sem_op=1;
semop(semid,&sobs,1);
shmctl(shmid1,IPC_RMID,0);
return 0;
}
So the problem is that if I put a sleep() above the DO SOMETHING in the second program, the first one will still go into the critical section, and it will finish before the second one, but the first one mustn't go into the critical section before the second one exits it, what can I do to prevent the first one from entering?