Locking semaphores in C problem sys/sem -


edit: peace of code pretty fine (so take example of semaphores ;). bug in program in place - found friend.

i have problem functions. 2 processes enter critical section. can't find problem in after spent 10 hours debugging. on should aim? there possibility have bud in piece of code?

    // lock semaphore     static int p(int sem_id)     {         struct sembuf sem_b;         sem_b.sem_num = 0;         sem_b.sem_op = -1; /* p() */         sem_b.sem_flg = 0;         if (semop(sem_id, &sem_b, 1) == -1) {               // error                  return(0);         }         return(1);     }      // unlock semaphore     static int v(int sem_id)     {         struct sembuf sem_b[1];         sem_b.sem_num = 0;         sem_b.sem_op = 1; /* v() */         sem_b.sem_flg = 0;         if (semop(sem_id, &sem_b, 1) == -1) {               // error             return(0);         }         return(1);     }      static int set_semval(int sem_id)  {         // set 1 (opened semaphore)         if (semctl(sem_id, 0, setval, 1) == -1) {               // error             return(0);         }         return(1);     }      static int get_val(int sem_id)     {         union semun sem_union;         //sem_union.val = 0; ?         return semctl(sem_id, 0, getval, sem_union);     } 

the action loop:

// semaphores init int mutex; if ((mutex=semget(key+2, 1, 0666))>=0) {     // semaphore exists     fprintf(stderr,"semaphore exists key %d\n", key+2); }  if ((mutex=semget(key+2, 1, 0666 | ipc_creat)) == -1) {      exit(exit_failure); } if (!set_semval(mutex)) {     exit(exit_failure); } fork()    // times conditionals  // in children while(1) {         p(mutex);            assert(get_val(mutex)==0); // ok         action();  // made 2 processes @ same time - fault         v(mutex); }    

pls, feel free edit question.

many thanks

in 'action loop' do if semaphore not exist?

currently 3rd parameter semget 0666 or permission_rw constant. may want use:

shmget(key, 1, permission_rw | ipc_creat);

this way if semaphore not exist create one.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -