Functions

daemon_init.c File Reference

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "portability.h"
#include "utility.h"
Include dependency graph for daemon_init.c:

Go to the source code of this file.

Functions

int gs_daemon_init (char *root, char *logfile)

Detailed Description

This file contains an implementation of daemon_init.

Definition in file daemon_init.c.


Function Documentation

int gs_daemon_init ( char *  root,
char *  logfile 
)

This makes the current process into a daemon. This was taken from the original NetSolve code which had adapted Stevens' version from "UNIX Network Programming" for use in NetSolve.

Parameters:
root -- The name of the directory to chdir to after starting as a daemon.
logfile -- The name of the file to open for logging. This file descriptor will be duplicated for stdout and stderr.
Returns:
0 on success, -1 on failure.

Definition at line 35 of file daemon_init.c.

                                          {
  pid_t pid;
  int fd;

  if(!root || !logfile)
    return -1;

  pid = fork();

  if(pid < 0)
    return -1;

  if(pid != 0) /* parent exits */
    exit(0);

  setsid();   /* become session leader */

  pid = fork();

  if(pid < 0)
    return -1;

  if(pid != 0) /* 1st child exits */
    exit(0);

  if(chdir(root) < 0) {
    perror("chdir()");
    return -1;
  }
  umask(0);

  /* Remap stdin to /dev/null */
  fd = open("/dev/null", O_RDWR|O_CREAT, 0644);
  if(fd < 0) {
    perror("open()");
    return -1;
  }
  close(0);
  if(dup2(fd, 0) < 0) {
    ERRPRINTF("dup2 failed\n");
    perror("dup2()");
    return -1;
  }
  close(fd);

  fprintf(stderr, "\n"
    "==============================================================\n"
    "|       -- Giving up terminal control! --\n|\n"
    "| All further terminal output will be sent to the log file:\n"
    "|\t\"%s\"\n"
    "=============================================================="
    "\n\n", logfile);

  /* Open logfile */
  remove(logfile);
  fd = open(logfile, O_RDWR|O_CREAT, 0644);
  if(fd < 0){
    ERRPRINTF("open failed\n");
    perror("open()");
    return -1;
  }

  /* Remap stdout and stderr to logfile */
  close(1);
  if(dup2(fd, 1) < 0){
    ERRPRINTF("dup2 failed\n");
    perror("dup2()");
    return -1;
  }
  close(2);
  if(dup2(fd, 2) < 0){
    ERRPRINTF("dup2 failed\n");
    perror("dup2()");
    return -1;
  }
  close(fd);

  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function: