Search code examples
cmemorysemaphoreshared

C Semaphores synchronization


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?


Solution

  • Typically program A should set the semaphore to 0 initially using semctl. Then program A calls semop with sobs.sem_op=-1, to wait on the semaphore.

    Program B doesn't need to do anything with the semaphore before "do something". (Note that A has to be run first, so that the semaphore is created and setup before B starts.) After B is done it should signal A by calling semop with sobs.sem_op=1.

    In short A sets up the semaphore and waits for it before "doing something". B "does something" and then signals the semaphore to wake A.