3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, 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('STATUSNET') && !defined('LACONICA')) {
26 var $daemonize = true;
29 function __construct($daemonize = true)
31 $this->daemonize = $daemonize;
52 * This prefers to Starting PHP 5.4 (dotdeb), maybe earlier for some version/distrib
53 * seems MySQL connection using mysqli driver get lost when fork.
54 * Need to unset it so that child process recreate it.
56 * @todo FIXME cleaner way to do it ?
58 global $_DB_DATAOBJECT;
59 unset($_DB_DATAOBJECT['CONNECTIONS']);
62 if ($pid < 0) { // error
63 common_log(LOG_ERR, "Could not fork.");
65 } else if ($pid > 0) { // parent
66 common_log(LOG_INFO, "Successfully forked.");
73 function alreadyRunning()
75 $pidfilename = $this->pidFilename();
81 if (!file_exists($pidfilename)) {
84 $contents = file_get_contents($pidfilename);
85 if (posix_kill(trim($contents), 0)) {
92 function writePidFile()
94 $pidfilename = $this->pidFilename();
100 return file_put_contents($pidfilename, posix_getpid() . "\n");
103 function clearPidFile()
105 $pidfilename = $this->pidFilename();
109 return unlink($pidfilename);
112 function pidFilename()
114 $piddir = common_config('daemon', 'piddir');
118 $name = $this->name();
122 return $piddir . '/' . $name . '.pid';
125 function changeUser()
127 $groupname = common_config('daemon', 'group');
130 $group_info = posix_getgrnam($groupname);
132 common_log(LOG_WARNING,
133 'Ignoring unknown group for daemon: ' . $groupname);
135 common_log(LOG_INFO, "Setting group to " . $groupname);
136 posix_setgid($group_info['gid']);
140 $username = common_config('daemon', 'user');
143 $user_info = posix_getpwnam($username);
145 common_log(LOG_WARNING,
146 'Ignoring unknown user for daemon: ' . $username);
148 common_log(LOG_INFO, "Setting user to " . $username);
149 posix_setuid($user_info['uid']);
156 if ($this->alreadyRunning()) {
157 common_log(LOG_INFO, $this->name() . ' already running. Exiting.');
161 if ($this->daemonize) {
162 common_log(LOG_INFO, 'Backgrounding daemon "'.$this->name().'"');
166 $this->writePidFile();
169 $this->clearPidFile();