title: How can I check the state of a semaphore in c?
body: <p>I have a global static variable that is a semaphore , since I'm writing a library and not a program . </p>
  
  <p>Within a <code>main()</code> program that uses the library there are invokes of <code>fork()</code> , and reading &amp; writing into/from a pipe , based on a shared memory . </p>
  
  <p>For example , this is <code>main()</code> that uses my library :</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include "my_pipe_shared_memory_based.h"
  int main()
  
  {
      int spd, pid, rb;
      char buff[4096];
      my_new_init();
  
      if (my_new_fifo("tmp_shm_pipe",0666) &lt; 0)
      {
          perror("my_new_fifo");
          exit(1);
      }
  
      if (fork()) 
      {
          spd = my_new_open("tmp_shm_pipe", O_RDONLY, 0600);
          if (spd &lt; 0)
          {
              perror("PARENT: my_new_open");
              exit(1);
          }
          rb = my_new_read(spd, buff, sizeof(buff));
          if (rb &gt; 0)
              write(1, buff, rb);
      }
  
      else
      {
          spd = my_new_open("tmp_shm_pipe", O_WRONLY, 0600);
          if (spd &lt; 0)
          {
              perror("SON: my_new_open");
              exit(1);
          }
          my_new_write(spd, "hello world!\n", sizeof("hello world!\n"));
      }
  
      my_new_close(spd);
      my_new_un_link("tmp_shm_pipe");
      my_new_finish();
  
      return 0;
  }
  </code></pre>
  
  <p>Now , I want to use a semaphore before each time that a process is <strong>reading and/or writing</strong> in the methods : </p>
  
  <ol>
  <li><p><strong>my_new_write()</strong></p></li>
  <li><p><strong>my_new_read()</strong></p></li>
  </ol>
  
  <p>Now , the question is , how can I check the state of the semaphore each time in the requested methods above (e.g. <code>my_new_write</code> &amp; <code>my_new_read</code>) , so I can let the process do his thing , or block it , if another process is currently reading/writing ? </p>
  
  <p>Thanks </p>