看前面黑咚咚,待俺上前杀它个干干净净。。。

 

Linux守护程序类-daemon

/////////////////////////////////////////////////////////////////////////////////////
///   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 ();
}

posted on 2013-05-14 14:01 山城,山 阅读(298) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

统计

常用链接

留言簿

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜