title: Using execl to execute a daemon
body: <p>I'm writing a program in C on Linux which includes a module that 
  allows a shell command to be executed on a remote machine.  The
  easiest way to actually execute the command would of course be to
  simply use the system() function, or use popen and then grab the
  output.  However, I chose to use a more low-level approach due to other design requirements which are not relevant to the current
  problem.</p>
  
  <p>So basically, I set up a pipe and fork, and then call execl.  This all
  works perfectly, except for one annoying exception.  It doesn't work
  properly if the shell command to be executed is a daemon.  In that
  case, it just hangs.  I can't figure out why.  My understanding is
  that when a daemon starts, it typically forks and then the parent exits.  Since my application has an open pipe to the parent, the call
  to read() should fail when the parent exits.  But instead
  the application just hangs.</p>
  
  <p>Here is some bare bones code that reproduces the problem:</p>
  
  <p><pre><code>
  int main(int argc, char** argv)
  {
          // Create a pipe and fork
          //
          int fd[2];
          int p = pipe(fd);
          pid_t pid = fork();</p>
  
  <pre><code>    if (pid &gt; 0)
      {
              // Read from the pipe and output the result
              //
              close(fd[1]);
              char buf[1024] = { 0 };
              read(fd[0], buf, sizeof(buf));
              printf("%s\n", buf);
  
              // Wait for child to terminate
              int status;
              wait(&amp;status);
      }
      else if (pid == 0)
      {
              // Redirect stdout and stderr to the pipe and execute the shell
              // command
              //
              dup2(fd[1], STDOUT_FILENO);
              dup2(fd[1], STDERR_FILENO);
              close(fd[0]);
              execl("/bin/sh", "sh", "-c", argv[1], 0);
      }
  </code></pre>
  
  <p>}
  </pre></code></p>
  
  <p>The code works fine if you use it with a normal shell command.  But if
  you try to run a daemon, it just hangs instead of returning to the
  prompt as it should. </p>