/////////////////////////////////////////////////////////////////////////////////////
/// daemon 测试类
#include <unistd.h>
#include <syslog.h>
#include <stdlib.h>
#include "daemon.h"
class logger : public daemon
{
public:
logger() : daemon("日志")
{}
void do_something()
{
while(true)
{
syslog (LOG_NOTICE, "Writing to my Syslog");
sleep(5);
}
}
};
int main(int argc, char *argv[]) {
logger l;
l.run();
return 0;
}
////////////////////////////////////////////////////////////////////////////
// .h
#ifndef DAEMON_H
#define DAEMON_H
#include <string>
class daemon{
public:
const std::string name;
public:
daemon(const char* nm);
void run();
private:
static void fork_off_parent();
static void set_child_context();
virtual void open_log();
virtual void do_something() =0;
virtual void finish();
private:
daemon(const daemon&);
daemon& operator=(const daemon&);
};
#endif // DAEMON_H
/////////////////////////////////////////////////////////////////////////////////
// .cpp
/*
* cp from http://shahmirj.com/blog/beginners-guide-to-creating-a-daemon-in-linux
*/
#include "daemon.h"
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
daemon::daemon(const char *nm) : name(nm)
{}
void daemon::run()
{
fork_off_parent();
set_child_context();
open_log();
do_something();
finish();
}
void daemon::fork_off_parent()
{
//Fork the Parent Process
pid_t pid = fork();
if (pid < 0)
{
exit(EXIT_FAILURE);
}
//We got a good pid, Close the Parent Process
if (pid > 0)
{
exit(EXIT_SUCCESS);
}
}
void daemon::set_child_context()
{
//Change File Mask
umask(0);
//Create a new Signature Id for our child
pid_t sid = setsid();
if (sid < 0)
{
exit(EXIT_FAILURE);
}
//Change Directory
//If we cant find the directory we exit with failure.
if ((chdir("/")) < 0)
{
exit(EXIT_FAILURE);
}
//Close Standard File Descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
void daemon::open_log()
{
//Set our Logging Mask and open the Log
setlogmask(LOG_UPTO(LOG_NOTICE));
openlog(name.c_str(), LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);
syslog(LOG_INFO, "Entering Daemon");
}
void daemon::finish()
{
//Close the log
closelog ();
}