title: Two-way communication between children and parent using signals
body: <p>I'm new to Linux and IPCs, so please bear with me.
  I'm stuck at a homework problem where I need to create a two-way communication system, which is:</p>
  
  <pre><code>1. Parent sends SIGUSR1 to multiple (1 to 10) children
  2. Children all respond with SIGUSR2 to parent
  3. If all SIGUSR2 signals are collected, parent pauses for 1 second
  4. Repeat from [1], until SIGTERM is sent to parent
  </code></pre>
  
  <p>Currently I'm just trying to get this working with just one child, and I need to use Parent.. and ChildHandler functions to handle acquired signals.</p>
  
  <p>I've tried sending initial SIGUSR1 to child and then using ChildHandler to <strong>kill(getppid(), SIGUSR)</strong> to parent, but this is not working as I expected it to. ChildHandler doesn't seem to receive the signal before Parent starts waiting.</p>
  
  <p><strong>ParentHandler(int signo)</strong> :</p>
  
  <pre><code>    if (signo == SIGUSR2)
      {
          printf("P received SIGUSR2\n");
  
          printf("Waiting for %d sec...\n\n", WAIT_TIME);
          sleep(WAIT_TIME);
          return;
      }
      else
      {
          printf("Something went wrong in PH...\n\n");
          exit(1);
      }
  </code></pre>
  
  <p><strong>ChildHandler(int signo)</strong> :</p>
  
  <pre><code>    if (signo == SIGUSR1)
          printf("C received SIGUSR1\n");
  
      kill(getppid(), SIGUSR2); // P &lt;--SIGUSR2--- C
  
      return;
  </code></pre>
  
  <p><strong>Main</strong> :</p>
  
  <pre><code>    pid_t pid, ppid;
      ppid = getpid();
  
      // Subscribe parent to SIGTERM
      // signal(SIGTERM, SigTermParentHandler);
  
      // Parent &lt;--&gt; Child dialogue
      if ((pid = fork()) != 0) // Parent
      {
          printf("P: %d | C: %d\n\n", ppid, pid);
  
          if (signal(SIGUSR2, ParentHandler) == SIG_ERR)
              printf("SIGUSR2 to parent was interrupted!");
  
          while (1)
          {
              printf("P ---SIGUSR1--&gt; C\n");
              kill(pid, SIGUSR1); // P ---SIGUSR1--&gt; C
          }
      }
      else // Child
      {
          sleep(WAIT_TIME); // Wait for parent to finish setting up
  
          if (signal(SIGUSR1, ChildHandler) == SIG_ERR)
              printf("SIGUSR1 to child was interrupted!");
      }
  </code></pre>
  
  <p>I expect output to be appx the following:</p>
  
  <pre><code>Parent PID is: 13918
  P: 13918 | C: 13919
  
  P ---SIGUSR1--&gt; C
  C received SIGUSR1
  P &lt;--SIGUSR2--- C
  P received SIGUSR2
  Waiting for 1 sec...
  
  P ---SIGUSR1--&gt; C
  ...
  </code></pre>