c - Shared memory secured write using semaphore -


below server code string shared memory variable.

client code display string available in shared memory.

full code : available in github link

server.c

int main(int argc, char *argv[]) {     /* code create posix shared memory , posix named semaphore */      /* critical section start */      snprintf(shared_msg->content, max_msg_length, "%s", argv[1]);      /* critical section end */ } 

client.c

int main(int argc, char *argv[]) {     /* code open posix shared memory , posix named semaphore */      for(i=0; i<20; i++){         /* critical section start */         //operation of semaphore         while(loop < 15){             printf("type : %d, content : %s\n", shared_msg->type, shared_msg->content);             sleep(1);             loop++;         }       /* critical section end */      loop = 0;     printf("loop %d finished\n", i);       } } 

how use( wait , post) posix semaphore in above code, achieve following requirement

  • when client starts has display shared memory data. once inner while loop finished client release shared memory.
  • if server start , try write data shared memory, when client while loop running, semaphore not write allow write untill client releases semaphore.
  • in single line server must write when client releases semaphore

thanks.

you want quasi-mutex or binary semaphore i.e. 1 process @ time can access resource, in case shared memory. looks wrong:

mysem = sem_open(semobj_path, o_creat | o_excl | o_rdwr, s_irwxu | s_irwxg, 2); 

you want initial value 1. first process wants write shared memory calls sem_wait decrementing ctr 0 thereby forcing other process calls sem_wait wait until value non-zero. in other words, semaphore locked until process holding sem_post.

your pseudo-code looks correct. sem_wait when enter critical section , sem_post when exit. think problem, understand it, lies in incorrectly initializing semaphore on sem_open.


Comments