#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <unistd.h>

int start_daemon(void)
  /* macht das ganze daemon-Zeugs */
  {
  if (chdir ("/tmp") < 0)     /* Basisverzeichnis des Daemons */
    return -1;
  if (setsid ( ) < 0)         /* Erzeugen einer neuen Prozessgruppe */
    return -1;
  umask(0);                   /* unmask the file mode */
  close(STDIN_FILENO);        /* Standarddateien schliessen */
  close(STDOUT_FILENO);
  close(STDERR_FILENO);

  /* Standarddateien auf /dev/null umleiten */
  open("/dev/null", O_RDWR);  /* stdin */
  dup(STDIN_FILENO);          /* stdout */
  dup(STDIN_FILENO);          /* stderr */

  /* hier kommt dann die grosse Daemon-Magie */
  for(;;)
    {
    sleep(10);
    }
  }

int main(void)
  {
  pid_t pid;     /* Prozess-Id des Kindes */

  if ((pid = fork()) < 0)
    {
    perror("fork() ging schief");
    return 1;
    }

  if (pid == 0)  /* dies ist der Kindprozess */
    {
    if (start_daemon() < 0)
      {
      perror("start_daemon() ging schief");
      return 1;
      }
    }
  else
    printf("Daemonprozess hat die ID %i\n", pid);
  return 0;
  }
