title: Using C to send an exec process to the background?
body: <p>My question sounds the same as this but it isn't:</p>
  
  <p><a href="https://stackoverflow.com/questions/3407197/start-a-process-in-the-background-in-linux-with-c">Start a process in the background in Linux with C</a></p>
  
  <p>I know how to do fork() but not how to send a process to the background. My program should work like a simple command unix shell that supports pipes and background processes. I could do pipe and fork but I don't know how to send a process to the background with <code>&amp;</code> like the last line of the program:</p>
  
  <pre><code>~&gt;./a.out uname
  SunOS
  ^C
  my:~&gt;./a.out uname &amp;
  </code></pre>
  
  <p>How to achieve the background process?</p>
  
  <pre><code>#include &lt;sys/types.h&gt;
  #include &lt;signal.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;errno.h&gt;
  
  #define TIMEOUT (20)
  
  int main(int argc, char *argv[])
  {
    pid_t pid;
  
    if(argc &gt; 1 &amp;&amp; strncmp(argv[1], "-help", strlen(argv[1])) == 0)
      {
        fprintf(stderr, "Usage: Prog [CommandLineArgs]\n\nRunSafe takes as arguments:\nthe program to be run (Prog) and its command line arguments (CommandLineArgs) (if any)\n\nRunSafe will execute Prog with its command line arguments and\nterminate it and any remaining childprocesses after %d seconds\n", TIMEOUT);
        exit(0);
      }
  
    if((pid = fork()) == 0)        /* Fork off child */
      {
        execvp(argv[1], argv+1);
        fprintf(stderr,"Failed to execute: %s\n",argv[1]);
        perror("Reason");
        kill(getppid(),SIGKILL);   /* kill waiting parent */
        exit(errno);               /* execvp failed, no child - exit immediately */
      }
    else if(pid != -1)
      {
        sleep(TIMEOUT);
        if(kill(0,0) == 0)         /* are there processes left? */
      {
        fprintf(stderr,"\Attempting to kill remaining (child) processes\n");
        kill(0, SIGKILL);      /* send SIGKILL to all child processes */
      }
      }
    else
      {
        fprintf(stderr,"Failed to fork off child process\n");
        perror("Reason");
      }
  }
  </code></pre>
  
  <p>The solution in plain English appears to be here:
  <a href="https://stackoverflow.com/questions/1618756/how-do-i-exec-a-process-in-the-background-in-c">How do I exec() a process in the background in C?</a></p>
  
  <blockquote>
    <p>Catch SIGCHLD and in the the handler, call wait().</p>
  </blockquote>
  
  <p>Am I on the right track?</p>