daemon()

Updated: April 19, 2023

Run a process in the background

Note: The daemon() function provides portability. In QNX Neutrino programs, use procmgr_daemon() instead.

See fork() to understand the implications of using daemon() instead of procmgr_daemon().

Synopsis:

#include <stdlib.h>

int daemon( int nochdir, 
            int noclose );

Arguments:

nochdir
If this argument is 0, the current working directory is changed to the root directory (/).
noclose
If this argument is 0, standard input, standard output, and standard error are redirected to /dev/null.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The daemon() function allows programs to detach themselves from the controlling terminal and run in the background as system daemons.

If daemon() is called with a noclose value of 0 and fails, then the states of file descriptors 0, 1, and 2 (STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO) are undefined.

Note: The controlling terminal behaves as in Unix System V, Release 4. An open() on a terminal device not already associated with another session causes the device to become the controlling terminal for that process.

If you are using the High Availability Manager (HAM), daemon() notifies the HAM of the new process change. If the calling process is being monitored, the HAM switches to monitor the new process that daemon() creates. For more information, see the High Availability Framework Developer's Guide.

Returns:

Zero for success, or -1 if an error occurs (errno is set).

Errors:

EAGAIN
Insufficient resources are available to create the child process. For example, you might have exceeded the maximum number of processes permitted; see the RLIMIT_NPROC resource for getrlimit().
EBADF
A problem occurred when daemon() was duplicating a file descriptor. For example, another thread might have opened or closed a file descriptor while the daemon() was occurring. You can add synchronization around the operations that involve file descriptors, or try calling daemon() again.
ENOMEM
The process requires more memory than the system is able to supply.
EPERM
One of the following occurred:
  • The calling process doesn't have PROCMGR_AID_FORK or PROCMGR_AID_PGRP abilities; see procmgr_ability().
  • (QNX Neutrino 7.0.1 or later) The calling process's priority is above the permitted range.
  • The process group ID of a process other than the calling process matches the process ID of the calling process. This is unlikely to occur.

Classification:

Legacy Unix

Safety:  
Cancellation point No
Interrupt handler No
Signal handler Yes
Thread See fork() for more information