从主循环调用守护进程函数?

时间:2014-11-05 21:05:29

标签: c++ linux

所以我正在编写一个程序,该程序将作为Linux系统中的后台进程运行,并且我已经设置了一个守护进程函数,以便开始运行该进程。背景。我需要知道的是我是否应该在主类中声明一个对象来运行守护进程函数,或者我是否应该使守护进程函数和它的两个子函数是静态的。代码在下面,有没有更好的方法来做这个或一种方法比另一种更优选?感谢。

#include "../Headers/LogMonitor.h"

#define RUNNING_DIR "/tmp"
#define LOCK_FILE   "exampled.lock"
#define LOG_FILE    "exampled.log"

LogMonitor::LogMonitor() {
    // TODO Auto-generated constructor stub

}

LogMonitor::~LogMonitor() {
    // TODO Auto-generated destructor stub
}

int main( int argc, const char* argv[] )
{
    // Daemonize the program to run in the background
    LogMonitor::daemonize();
}

void LogMonitor::signal_handler(int sig)
{
    switch(sig) {
    case SIGHUP:
        log_message(LOG_FILE,"hangup signal caught");
        break;
    case SIGTERM:
        log_message(LOG_FILE,"terminate signal caught");
        exit(0);
        break;
    }
}

void LogMonitor::log_message(const char *filename, const char *message)
{
    FILE *logfile;
    logfile=fopen(filename,"a");
    if(!logfile) return;
    fprintf(logfile,"%s\n",message);
    fclose(logfile);
}

void LogMonitor::daemonize()
{
    int i,lfp;
    char str[10];

    if(getppid()==1) return;    // Check if already a daemon

    i = fork();
    if (i < 0) exit(1);         // Fork error
    if (i > 0) exit(0);         // Parent exits

    setsid();                   // Obtain a new process group

    for (i = getdtablesize(); i >= 0; --i) close(i);    // Close all descriptors

    i = open("/dev/null",O_RDWR);                       // stdin
    dup(i);                                             // stdout
    dup(i);                                             // stderr

    umask(027);                                         // Set newly created file permissions

    chdir(RUNNING_DIR);                                 // Change running directory

    lfp = open("exampled.lock",O_RDWR|O_CREAT,0640);
    if (lfp < 0) exit(1);                               // Can't open
    if (lockf(lfp,F_TLOCK,0) < 0) exit(0);              // Can't lock
    sprintf(str,"%d\n", getpid());
    write(lfp,str,strlen(str));                         // Record pid to lockfile

    signal(SIGCHLD,SIG_IGN);                            // Ignore child
    signal(SIGTSTP,SIG_IGN);                            // Ignore tty signals
    signal(SIGTTOU,SIG_IGN);
    signal(SIGTTIN,SIG_IGN);
    signal(SIGHUP,  LogMonitor::signal_handler);                    // Catch hangup signal
    signal(SIGTERM, LogMonitor::signal_handler);                    // Catch kill signal
}

1 个答案:

答案 0 :(得分:2)

现代守护进程不应该自己背景。相反,只需在前台运行它,让调用者(即/etc/init.d下的脚本)选择守护它 - start-stop-daemon(8)是常用的,尽管{{1}可以自己做。