title: Synchronizing two child processes with semaphores in c
body: <p>I have to create a program that synchronizes two processes each printing only a single letter so that whenever we observe the output of the program, the difference between the amount of <code>"A"</code> and <code>"B"</code> is no greater than 2.</p>
  
  <p>So this would be accepted:</p>
  
  <pre><code>BAABBAABBABA
  </code></pre>
  
  <p>this wouldn't be because it prints 4 B's and only 2 A's:</p>
  
  <pre><code>ABBABB
  </code></pre>
  
  <p>So for starters i decided to use the POSIX semaphores.
  I created two semaphores , giving them all the permissions using the <code>sem_open</code>
  Then i created two child processes and for each child process i open the semaphores i created as described in the man page for <code>sem_open</code> and manipulate them.</p>
  
  <p>I don't think it's the logic of the <code>sem_post</code> and <code>sem_wait</code> that's at fault here, since the program seems to ignore them.</p>
  
  <p>So my question is. What goes wrong?</p>
  
  <p>Edit: I don't really need the solution to the problem. Some guidance alone would be much appreciated and welcoming as an answer. Thank you in advance!</p>
  
  <pre><code>#include &lt;sys/stat.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;ctype.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;fcntl.h&gt;
  #include &lt;semaphore.h&gt;
  
  int main(void){
  
  
  
    sem_t *semA = sem_open("/semA", O_CREAT|O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO, 0);   //Initialize semaphore(= 0) for process A
    sem_t *semB = sem_open("/semB", O_CREAT|O_EXCL, S_IRWXU | S_IRWXG | S_IRWXO, 0);   //Initialize semaphore(= 0) for process B
  
  
    if (fork()){      // parent process
      if(fork()){}
      else{
        sem_t *childsemA = sem_open("/semA", 0);
        sem_t *childsemB = sem_open("/semB", 0);
        while(1){
          printf("A");
          sem_post(childsemB);
          sem_wait(childsemA);
        }
      }
    }
    else{
      sem_t *childsemA = sem_open("/semA", 0);
      sem_t *childsemB = sem_open("/semB", 0);
      while(1){
        printf("B");    // child2 process
        sem_post(childsemA);
        sem_wait(childsemB);
      }
    }
  
    return 0;
  }
  </code></pre>
  
  <p>Output:</p>
  
  <p><a href="https://i.stack.imgur.com/b61wd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b61wd.png" alt="enter image description here"></a></p>