title: Execute background process and check status from parent
body: <p>I'm currently trying to:</p>
  
  <ol>
  <li>Execute a background process with a fork() call and execvp() inside the children.</li>
  <li>If the call to execvp() was successful, adding the PID of the child process to a list.</li>
  <li>If the call to execvp() returned -1 (error), do not add the PID to the list.</li>
  </ol>
  
  <p>My problem is: if execvp() returns -1 (for instance, if the executable isn't found) I can't "communicate" with the parent proccess since I'm inside the child process in the fork(). And if I use waitpid() to wait for the child, I'm not running a background process (since I lose the concurrency).</p>
  
  <p>I tried using WNOHANG and checking *status with (WEXITSTATUS(status) == 1) but it doesn't work (since the parent process executes "instantly" and doesn't know if the child has exited yet, or that's what I think)</p>
  
  <p>My current code:</p>
  
  <pre><code>void background(char *vector[]) {
  pid_t childp;
  int status;
  childp=fork();
      if (childp==-1){ 
          perror("Error using fork \n");
          return;
      }
      if (childp==0) { //Child process
          if (execvp(vector[0],vector)==-1) {
              perror("exec");
              exit(1);
          }
      }
  waitpid(-1, &amp;status, WNOHANG);
  if(WIFEXITED(status)) {
      //Child exited
      if (WEXITSTATUS(status) == 1) {
          //Child exited with error
          return;
      }
  }
  if (insertProcess(childp,vector)==-1)
      perror("Full list");
  else
      updateList();   
  }
  </code></pre>
  
  <p>The only solution I've found at the moment is inserting a sleep(1) call before waitpid (Source: <a href="https://stackoverflow.com/a/26617152/1339354">https://stackoverflow.com/a/26617152/1339354</a> ), but this looks more like a hack than something well done. Any other ideas?</p>