title: waitpid() function returns ERROR (-1), why?
body: <p>I'm writing a Linux shell-like program in C.</p>
  <p>Among others, I'm implementing two built-in commands: <code>jobs, history.</code>
  In <code>jobs</code>, I print the list of currently working commands (in the background).
  In <code>history</code> I print the list of all commands history until now, specifying for each command if it's RUNNING or DONE.</p>
  <p>To implement the two, my idea was to have a list of commands, mapping the command name to their PID. Once the jobs/history command is called, I run through them, check which ones are running or done, and print accordingly.</p>
  <p>I read online that the function: <code>waitpid(pid, &amp;status, WNOHANG)</code>, can detect from &quot;PID&quot; whether a process is still running or done, without stopping the process.
  It works well, except for this:</p>
  <p>When a program is alive, the function returns it.
  When a program is done, the first time I call it returns done, and from there on, if called again with the same PID, it returns -1 (ERROR).</p>
  <p>For example, it would look like this: (the &amp; symbolizes background command)</p>
  <pre><code>$ sleep 3 &amp;
  $ jobs
  sleep ALIVE 
  $ jobs  (withing the 3 seconds)
  sleep ALIVE
  $ jobs (after 3 seconds)
  sleep DONE
  $ jobs 
  sleep ERROR
  $ jobs 
  sleep ERROR
  ....
  </code></pre>
  <p>Also, these are not influenced by other command calls I might do before or after, it seems the behavior described above is independent of other commands.</p>
  <p>I read online various reasons why <code>waitpid</code> might return -1, but I wasn't able to identify the reason in my case. Also, I tried looking for how to understand what type of <code>waitpid</code> error is it, but again unsuccessfully.</p>
  <p><strong>My questions are:</strong></p>
  <ol>
  <li>Why do you think this behavior is happening</li>
  <li>If you have a solution (the ideal thing would it for it to keep returning DONE)</li>
  <li>If you have a better idea of how to implement the jobs/history command is well accepted</li>
  </ol>
  <p>One solution for this problem is that as soon as I get &quot;DONE&quot;, I sign the command as DONE, and don't perform the <code>waitid</code> anymore on it before printing it. This would solve the issue, but I would remain in the dark as to WHY is this happening</p>