Subject: Postmaster as a Daemon

From: [email-masked]
Date: Thu, 18 Mar 93 15:03:00 -0800

The (4.0.1) Postmaster is intended to be run as a daemon, but it
doesn't take any care to make itself a daemon.  For example it doesnt
make itself a session leader or try to divorce itself from a
controlling TTY.

Is this intention or oversight?

Rather than change the postmaster code I cobbled this short hack and
run Postmaster this way...  Perhaps this code (excluding the exec)
should be put into Postmaster's main()?

-=-=-=-=-=
/* daemonize.c -- Daemonize some program. */

/*
  This code causes some other program to become a daemon.

  usage: daemonize command args

  Author: Robert Withrow ([email-masked]). (Adapted from Stevens)
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>

main(int argc, char *argv[])
{
  pid_t pid;
  int fd;
  
  /* Check args */

  if (argc <= 1) {
    fprintf(stderr,"Usage: %s command <args>\n",argv[0]);
    exit(EXIT_FAILURE);
  }

  /* Fork first time */

  if ((pid = fork()) < 0)		/* Fork */
    exit(EXIT_FAILURE);			/* If error just quit */
  else if (pid != 0)			/* If we are parent */
    exit(EXIT_SUCCESS);			/* Exit */

  /* Now, as child, become session leader */

  setsid();
  
  /* Fork again to prevent ever getting a control terminal */

  if ((pid = fork()) < 0)		/* Fork */
    exit(EXIT_FAILURE);			/* If error just quit */
  else if (pid != 0)			/* If we are parent */
    exit(EXIT_SUCCESS);			/* Exit */

  /* Now, change default dir and make all fds go to /dev/null */
  /* Could add logging here */

  chdir("/");
  umask(0);
  fd = open("/dev/null",O_RDWR);
  dup2(fd,0);
  dup2(fd,1);
  dup2(fd,2);
  close(fd);

  /* Now exec the real program */
  
  execvp(argv[1],&argv[1]);
  exit(EXIT_FAILURE);			/* Should never get here */
}
---
 Robert Withrow, Tel: +1 617 598 4480, Fax: +1 617 598 4430, Net: [email-masked]
 R.W. Withrow Associates, 21 Railroad Ave, Swampscott MA 01907-1821 USA