简体   繁体   中英

Putting a semaphore in shared memory C

I am trying to make a semaphore visible to multiple processes after forking. This is the dining philosopher's problem using shared memory and a semaphore to ensure only one philosopher picks up chopsticks at a time (not the most efficient way, an array of semaphores would be more efficient, but that is not the point). It is getting to the while loop inside of start, printing out that it entered, but none of the processes are entering the if statement by any process. Global scope: int semId;

Inside my main:

semId=semget(IPC_PRIVATE,1,S_IRUSR|S_IWUSR);
for(int i =0; i<5; i++)
   if(fork()==0)
        start(i);


void start(int philNo){
    struct sembuf semWait[1]={{0,-1,0}};
    struct sembuf semSignal[1] = {{0,1,0}};
     while(philArr[philNo].stomach<100){

      printf("entered while\n");
      //see if the semaphore is available
      if (semop(semId,semWait,1)==0)
        {
          printf("semaphore available/n");
        }

Full code available here: http://pastie.org/10054082 There are somethings declared at the global that shouldn't be but that will be cleaned up once I get it working

The semaphore starts out with a 0 count. So somebody has to semSignal to get the ball rolling. I put a semSignal in main after the loop that forks the children, and that allowed the children to get the semaphore.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM