linux守护程序

来源:互联网 发布:软件大全 编辑:程序博客网 时间:2024/06/04 18:25
<pre name="code" class="cpp">//============================================================================// Name        : forkdemo.cpp// Author      : // Version     :// Copyright   : Your copyright notice// Description : Hello World in C++, Ansi-style//============================================================================#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <syslog.h>#include <errno.h>#include <pwd.h>#include <signal.h>#include <string.h>#include <iostream>#include <string>#include <boost/filesystem.hpp>//http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html//http://www.enderunix.org/docs/eng/daemon.php//http://www.ics.uzh.ch/~dpotter/howto/daemonizetypedef std::string STRING;#define DAEMON_NAME  "jsonservice"typedef struct {    bool isrun;    int lfp;} Se_LinuxRunInfo;static Se_LinuxRunInfo g_run;void signal_handler(int sig) {    switch (sig) {        case SIGTERM:            g_run.isrun = false;            break;    }}void clean_lockfile(const char *lockfile) {    close(g_run.lfp);    boost::filesystem::path pidfile(lockfile);    if (boost::filesystem::exists(pidfile))        boost::filesystem::remove(pidfile);}void daemonize(const char *lockfile) {    pid_t pid, sid;    /* already a daemon */    if (getppid() == 1) {        syslog(LOG_ERR, "already a daemon");        exit(EXIT_FAILURE);    }    /* Fork off the parent process */    pid = fork();    if (pid < 0) {        syslog(LOG_ERR, "unable to fork daemon, code=%d (%s)", errno, strerror(errno));        exit(EXIT_FAILURE);    }    /* If we got a good PID, then we can exit the parent process. */    if (pid > 0)        exit(EXIT_SUCCESS);    /* Change the file mode mask */    umask(0);    /* Create a new SID for the child process */    sid = setsid();    if (sid < 0) {        syslog(LOG_ERR, "unable to create a new session, code %d (%s)", errno, strerror(errno));        exit(EXIT_FAILURE);    }    /* close all descriptors */    for (int i = getdtablesize(); i >= 0; --i)        close(i);    /* Change the current working directory.  This prevents the current directory from being locked; hence not being able to remove it. */    if ((chdir("/")) < 0) {        syslog(LOG_ERR, "unable to change directory to %s, code %d (%s)", "/", errno, strerror(errno));        exit(EXIT_FAILURE);    }    /* Create the lock file as the current user */    g_run.lfp = open(lockfile, O_RDWR | O_CREAT, 0640);    if (g_run.lfp < 0) {        syslog(LOG_ERR, "unable to create lock file %s, code=%d (%s)", lockfile, errno, strerror(errno));        exit(EXIT_FAILURE);    }    if (lockf(g_run.lfp, F_TLOCK, 0) < 0) {        clean_lockfile(lockfile);        syslog(LOG_ERR, "can not lock");        exit(EXIT_FAILURE);    }    char str[32];    snprintf(str, 32, "%d\n", getpid()); /* first instance continues */    write(g_run.lfp, str, strlen(str)); /* record pid to lockfile */    /* Trap signals that we expect to recieve */    signal(SIGCHLD, SIG_IGN); /* ignore child */    signal(SIGTSTP, SIG_IGN); /* ignore tty signals */    signal(SIGTTOU, SIG_IGN);    signal(SIGTTIN, SIG_IGN);    signal(SIGHUP, SIG_IGN); /* catch hangup signal */    //signal(SIGTERM, signal_handler); /* catch kill signal */    void (*prev_handler)(int);    prev_handler = signal(SIGTERM, signal_handler);    if (SIG_ERR == prev_handler) {        clean_lockfile(lockfile);        syslog(LOG_ERR, "bind signal fail! ");        exit(EXIT_FAILURE);    }}void exec_linux() {    openlog(DAEMON_NAME, LOG_PID, LOG_LOCAL5);    syslog(LOG_INFO, "starting....");    boost::system::error_code ec;    boost::filesystem::path curPath = boost::filesystem::current_path(ec);    if (ec) {        syslog(LOG_INFO, "failed to get the program running path!");        exit(EXIT_FAILURE);    }    STRING strPath = curPath.string();    strPath += "/";    strPath += DAEMON_NAME;    strPath += ".pid";    /* One may wish to process command line arguments here */    /* Daemonize */    daemonize(strPath.c_str());    /* Now we are a daemon -- do the work for which we were paid */    g_run.isrun = true;    while (g_run.isrun)        sleep(100); /* run */    /* Finish up */    clean_lockfile(strPath.c_str());    syslog(LOG_NOTICE, "terminated");    closelog();}int main() {    exec_linux();    return 0;}



#!/bin/sh#description:jsonservice serviceRETVAL=0start(){echo -n "jsonservice serive is start...\n"cd /home/renlai/exec./GeometryService}stop(){echo "jsonservice service is stoped..."while read LINEdo         kill $LINEdone < /home/renlai/exec/jsonservice.pid#killall -9 GeometryService}case $1 instart)start;;stop)stop;;*)echo "Usage: $0 (start|stop|restart)";;esacexit $RETVALsudo chmod +x /etc/init.d/jsonservicesudo update-rc.d jsonservice start 99 2 3 4 5 . stop 18 0 1 6 .


                                             
0 0
原创粉丝点击