title: Shared memory secured write using semaphore
body: <p>Below Server code which a string into shared memory variable.</p>
  
  <p>Client code display the string available in shared memory.</p>
  
  <p>FULL Code : <a href="https://github.com/sujinsr/linux/blob/master/sema/server.c" rel="nofollow">available in this github link</a></p>
  
  <p>Server.c</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
      /* code to create posix shared memory and posix named semaphore */
  
      /* critical section start */
  
      snprintf(shared_msg-&gt;content, MAX_MSG_LENGTH, "%s", argv[1]);
  
      /* critical section end */
  }
  </code></pre>
  
  <p>Client.c</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
      /* code to open posix shared memory and posix named semaphore */
  
      for(i=0; i&lt;20; i++){
          /* critical section start */
  
         //operation of semaphore
          while(loop &lt; 15){
              printf("Type : %d, content : %s\n", shared_msg-&gt;type, shared_msg-&gt;content);
              sleep(1);
              loop++;
          }
  
       /* Critical section end */
  
      loop = 0;
      printf("loop %d finished\n", i);
        }
  }
  </code></pre>
  
  <p>How to use( wait and post) POSIX semaphore in above code, to achieve following requirement</p>
  
  <ul>
  <li>When client starts it has to display shared memory data. once inner while loop finished then only client release the shared memory.</li>
  <li>If server start and try to write data to shared memory, when client while loop running, semaphore will not write allow the to write untill client releases the semaphore.</li>
  <li>In single line Server must write when client releases the semaphore</li>
  </ul>
  
  <p>Thanks.</p>