Newer
Older
Copyright (C) 2008 Sebastien LUTTRINGER <contact@seblu.net>
SLS is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
SLS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SLS; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "sls.hh"
#include "option.hh"
#include "database.hh"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
// Daemonize
if (O.daemon) {
// open log file
int logfd = open(O.logfile.c_str(), O_WRONLY | O_APPEND | O_CREAT, 0640);
if (logfd < 0)
throw Error(ERR_FILE, "Cannot open " + O.logfile + ": " + strerror(errno));
// redirect stdout and stderr
if (dup2(logfd, STDOUT_FILENO) == -1)
throw Error(ERR_FILE, (string) "Unable to redirect STDOUT into " + O.logfile + ": " + strerror(errno));
if (dup2(logfd, STDERR_FILENO) == -1)
throw Error(ERR_FILE, (string) "Unable to redirect STDERR into " + O.logfile + ": " + strerror(errno));
// close unused fd
if (close(STDIN_FILENO) == -1)
throw Error(ERR_FILE, (string) "Unable to close STDIN: " + strerror(errno));
if (close(logfd) == -1)
throw Error(ERR_FILE, (string) "Unable to close: " + O.logfile + ": " + strerror(errno));
// goto hell
daemon(0, 1);
}
// Options print
if (O.verbose) {
if (!isatty(STDOUT_FILENO)) {
time_t t = time(0);
std::cout << "-------------------------------------" << std::endl
<<"sls start at " << ctime(&t);
}
O.print(std::cout);
}
// Close server if started
if (S.started())
S.stop();
// Save data in database
if (D.opened())
D.close();
// print error
// Print exit code if in daemon and verbose mode
if (O.daemon && O.verbose) std::cerr << "Exit with code: " << e.code() << std::endl;