3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, Control Yourself, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('LACONICA')) {
26 var $daemonize = true;
28 function __construct($daemonize = true)
30 $this->daemonize = $daemonize;
41 if ($pid < 0) { // error
42 common_log(LOG_ERR, "Could not fork.");
44 } else if ($pid > 0) { // parent
45 common_log(LOG_INFO, "Successfully forked.");
52 function alreadyRunning()
54 $pidfilename = $this->pidFilename();
60 if (!file_exists($pidfilename)) {
63 $contents = file_get_contents($pidfilename);
64 if (posix_kill(trim($contents), 0)) {
71 function writePidFile()
73 $pidfilename = $this->pidFilename();
79 return file_put_contents($pidfilename, posix_getpid() . "\n");
82 function clearPidFile()
84 $pidfilename = $this->pidFilename();
88 return unlink($pidfilename);
91 function pidFilename()
93 $piddir = common_config('daemon', 'piddir');
97 $name = $this->name();
101 return $piddir . '/' . $name . '.pid';
104 function changeUser()
106 $username = common_config('daemon', 'user');
109 $user_info = posix_getpwnam($username);
111 common_log(LOG_WARNING,
112 'Ignoring unknown user for daemon: ' . $username);
114 common_log(LOG_INFO, "Setting user to " . $username);
115 posix_setuid($user_info['uid']);
119 $groupname = common_config('daemon', 'group');
122 $group_info = posix_getgrnam($groupname);
124 common_log(LOG_WARNING,
125 'Ignoring unknown group for daemon: ' . $groupname);
127 common_log(LOG_INFO, "Setting group to " . $groupname);
128 posix_setgid($group_info['gid']);
135 if ($this->alreadyRunning()) {
136 common_log(LOG_INFO, $this->name() . ' already running. Exiting.');
140 if ($this->daemonize) {
141 common_log(LOG_INFO, 'Backgrounding daemon "'.$this->name().'"');
145 $this->writePidFile();
148 $this->clearPidFile();