Back to DaemonApplication class

Method daemonize

protected bool
daemonize
()
Method to put the application into the background.
Returns
  • bool
Since
  • 1.7.0
-
  • \RuntimeException

Method daemonize - Source code

/**
 * Method to put the application into the background.
 *
 * @return  boolean
 *
 * @since   1.7.0
 * @throws  \RuntimeException
 */
protected function daemonize()
{
    // Is there already an active daemon running?
    if ($this->isActive()) {
        Log::add($this->name . ' daemon is still running. Exiting the application.', Log::EMERGENCY);
        return false;
    }
    // Reset Process Information
    $this->safeMode = !!@ini_get('safe_mode');
    $this->processId = 0;
    $this->running = false;
    // Detach process!
    try {
        // Check if we should run in the foreground.
        if (!$this->input->get('f')) {
            // Detach from the terminal.
            $this->detach();
        } else {
            // Setup running values.
            $this->exiting = false;
            $this->running = true;
            // Set the process id.
            $this->processId = (int) posix_getpid();
            $this->parentId = $this->processId;
        }
    } catch (\RuntimeException $e) {
        Log::add('Unable to fork.', Log::EMERGENCY);
        return false;
    }
    // Verify the process id is valid.
    if ($this->processId < 1) {
        Log::add('The process id is invalid; the fork failed.', Log::EMERGENCY);
        return false;
    }
    // Clear the umask.
    @umask(0);
    // Write out the process id file for concurrency management.
    if (!$this->writeProcessIdFile()) {
        Log::add('Unable to write the pid file at: ' . $this->config->get('application_pid_file'), Log::EMERGENCY);
        return false;
    }
    // Attempt to change the identity of user running the process.
    if (!$this->changeIdentity()) {
        // If the identity change was required then we need to return false.
        if ($this->config->get('application_require_identity')) {
            Log::add('Unable to change process owner.', Log::CRITICAL);
            return false;
        } else {
            Log::add('Unable to change process owner.', Log::WARNING);
        }
    }
    // Setup the signal handlers for the daemon.
    if (!$this->setupSignalHandlers()) {
        return false;
    }
    // Change the current working directory to the application working directory.
    @chdir($this->config->get('application_directory'));
    return true;
}