The Linux Programming Interface

(nextflipdebug5) #1

770 Chapter 37


Listing 37-1: Header file for become_daemon.c
––––––––––––––––––––––––––––––––––––––––––––––––––– daemons/become_daemon.h
#ifndef BECOME_DAEMON_H /* Prevent double inclusion */
#define BECOME_DAEMON_H

/* Bit-mask values for 'flags' argument of becomeDaemon() */

#define BD_NO_CHDIR 01 /* Don't chdir("/") */
#define BD_NO_CLOSE_FILES 02 /* Don't close all open files */
#define BD_NO_REOPEN_STD_FDS 04 /* Don't reopen stdin, stdout, and
stderr to /dev/null */
#define BD_NO_UMASK0 010 /* Don't do a umask(0) */

#define BD_MAX_CLOSE 8192 /* Maximum file descriptors to close if
sysconf(_SC_OPEN_MAX) is indeterminate */

int becomeDaemon(int flags);

#endif
––––––––––––––––––––––––––––––––––––––––––––––––––– daemons/become_daemon.h
The implementation of the becomeDaemon() function is shown in Listing 37-2.

The GNU C library provides a nonstandard function, daemon(), that turns the
caller into a daemon. The glibc daemon() function doesn’t have an equivalent of
the flags argument of our becomeDaemon() function.

Listing 37-2: Creating a daemon process
––––––––––––––––––––––––––––––––––––––––––––––––––– daemons/become_daemon.c
#include <sys/stat.h>
#include <fcntl.h>
#include "become_daemon.h"
#include "tlpi_hdr.h"

int /* Returns 0 on success, -1 on error */
becomeDaemon(int flags)
{
int maxfd, fd;

switch (fork()) { /* Become background process */
case -1: return -1;
case 0: break; /* Child falls through... */
default: _exit(EXIT_SUCCESS); /* while parent terminates */
}

if (setsid() == -1) /* Become leader of new session */
return -1;

switch (fork()) { /* Ensure we are not session leader */
case -1: return -1;
case 0: break;
default: _exit(EXIT_SUCCESS);
}
Free download pdf