守护进程

守护进程就是生存期长的一种进程,没有控制终端,就像是在后台运行,进程ID等于进程组ID 等于会话ID

1.编写规则

(1).调用umask码设为0 直接调用umask()函数

umask(0);

(2).将父进程退出

pid_t pid;
pid = fork();
if(pid < 0)
{   
    perror("fork()");
    return -1; 
}   
if(pid > 0)
    exit(0);

(3).调用setsid创建一个新的会话,调用进程成为新会话的首进程,新的进程组组长,并且没有控制终端

if (setsid() == -1) 
{
    perror("setsid()");
    return -1; 
}   
 // PID == PGID == SID no tty

(4).将调用进程的工作目录改为根目录

chdir("/");

(5).关闭不需要的文件描述符

(6).将文件描述符0,1,2 指向 /dev/null

fd = open("/dev/null", O_RDWR);
if (fd == -1) 
{
    perror("open()");
    return -1; 
}
dup2(fd, 0); 
dup2(fd, 1); 
dup2(fd, 2); 

2.守护进程库函数

daemon(3)

#include <unistd.h>
int daemon(int nochdir, int noclose);

If nochdir is zero, daemon() changes the process's current working directory to the root directory ("/"); otherwise, the current working directory is left unchanged.

当nochdir为0的时候,将工作目录改为“/”目录

If noclose is zero, daemon() redirects standard input, standard output and standard error to /dev/null; otherwise, no changes are made to these file descriptors.

当noclise为0的时候,将文件描述符为1,2,3的指向/dev/null

返回值:

成功返回0;失败返回-1并且设置errno

3.出错记录

#include <syslog.h>
void openlog(const char *ident, int option, int facility);
void syslog(int priority, const char *format, ...);
void closelog(void);

openlog()

打开与日志的连接(ubuntu下守护进程日志路径“/var/log/syslog”)。 ident指向的字符串前置于每条消息,通常设置为程序名称。 如果ident为NULL,则使用程序名称。

option可选项

LOG_CONS Write directly to system console if there is an error while sending to system logger.

LOG_NDELAY Open the connection immediately (normally, the connection is opened when the first message is logged).

LOG_NOWAIT Don't wait for child processes that may have been created while logging the message. (The GNU C library does not create a child process,so this option has no effect on Linux.)

LOG_ODELAY The converse of LOG_NDELAY; opening of the connection is delayed until syslog() is called. (This is the default, and need not be specified.)

LOG_PERROR (Not in POSIX.1-2001 or POSIX.1-2008.) Print to stderr as well.

LOG_PID Include PID with each message.

facility

​ 可选项查看man手册

具体用法

openlog(NULL, LOG_PID | LOG_PERROR, LOG_DAEMON);
fp = fopen(FLNAME, "w");
    if (NULL == fp) 
    {
        // perror("fopen()");
        syslog(LOG_ERR, "fopen():%s", strerror(errno));
        exit(1);
    }
    while (1) 
    {
        time(&tm);
        tmp = localtime(&tm);
        if (NULL == tmp) 
        {
            // fprintf(stderr, "localtime() failed\n");
            syslog(LOG_ERR, "localtime() failed");
            goto ERROR;
        }
        strftime(buf, BUFSIZE, "%Y-%m-%d %H:%M:%S\n", tmp);
        fputs(buf, fp);
        // 调试
        syslog(LOG_INFO, "%s write into the file %s", buf, FLNAME);
        fflush(NULL);
        sleep(1);
    }

    fclose(fp);

4.单实例守护进程

​ 一个守护进程可以开启多个,如果加以限制,只能开启一个,就是单实例守护进程

static int single_instance(void)
{
    int fd;
    char buf[BUFSIZE] = {};

    fd = open(DAEMON_FILE, O_RDWR | O_CREAT, 0666);
    if (fd < 0) {
        syslog(LOG_ERR, "open():%s", strerror(errno));
        return -1;
    }

    if (lockf(fd, F_TLOCK, 0) < 0) {
        if (errno == EACCES || errno == EAGAIN) {
            // 已被占用
            close(fd);
            return -1;
        }
        syslog(LOG_ERR, "lockf():%s", strerror(errno));
        exit(1);
    }

    ftruncate(fd, 0);
    snprintf(buf, BUFSIZE, "%d", getpid());
    write(fd, buf, strlen(buf));
}

综合程序

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <syslog.h>
#include <errno.h>
#include <string.h>

#define BUFSIZE 1024
#define FLNAME  "/tmp/out"

#define DAEMON_FILE "/var/run/daemon.pid"

static int mydaemon(void);
static int single_instance(void);
int main(void)
{
    time_t tm;
    struct tm *tmp = NULL;
    char buf[BUFSIZE] = {};
    FILE *fp = NULL;

    // 守护进程
#if 0
    if (mydaemon() < 0) {
        fprintf(stderr, "daemon failed\n");
        exit(1);
    }
#endif

    // 提交日志
    openlog(NULL, LOG_PID | LOG_PERROR, LOG_DAEMON);

#if 1
    if (daemon(0, 0) == -1) {
        perror("daemon()");
        exit(1);
    }
#endif

    // 单实例
    if (single_instance() < 0) {
        syslog(LOG_ERR, "single_instance() failed");
        exit(1);
    }

    fp = fopen(FLNAME, "w");
    if (NULL == fp) {
        // perror("fopen()");
        syslog(LOG_ERR, "fopen():%s", strerror(errno));
        exit(1);
    }

    while (1) {
        time(&tm);
        tmp = localtime(&tm);
        if (NULL == tmp) {
            // fprintf(stderr, "localtime() failed\n");
            syslog(LOG_ERR, "localtime() failed");
            goto ERROR;
        }
        strftime(buf, BUFSIZE, "%Y-%m-%d %H:%M:%S\n", tmp);
        fputs(buf, fp);
        // 调试
        syslog(LOG_INFO, "%s write into the file %s", buf, FLNAME);
        fflush(NULL);   
        sleep(1);
    }

    fclose(fp);
    closelog();
    exit(0);
ERROR:
    closelog();
    fclose(fp);
    exit(1);
}

static int mydaemon(void)
{
    pid_t pid;
    int fd;

    pid = fork();
    if (pid < 0) {
        perror("fork()");
        return -1;
    }
    if (pid > 0) 
        exit(0);
    if (setsid() == -1) {
        perror("setsid()");
        return -1;
    }
    // PID == PGID == SID no tty
    
    fd = open("/dev/null", O_RDWR);
    if (fd == -1) {
        perror("open()");
        return -1;
    }
    dup2(fd, 0);
    dup2(fd, 1);
    dup2(fd, 2);

    if (fd > 2)
        close(fd);

    umask(0);
    chdir("/");

    return 0;   
}

// 单实例
static int single_instance(void)
{
    int fd;
    char buf[BUFSIZE] = {};

    fd = open(DAEMON_FILE, O_RDWR | O_CREAT, 0666);
    if (fd < 0) {
        syslog(LOG_ERR, "open():%s", strerror(errno));          
        return -1;
    }

    if (lockf(fd, F_TLOCK, 0) < 0) {
        if (errno == EACCES || errno == EAGAIN) {
            // 已被占用
            close(fd);
            return -1;
        }
        syslog(LOG_ERR, "lockf():%s", strerror(errno));
        exit(1);
    }

    ftruncate(fd, 0);   
    snprintf(buf, BUFSIZE, "%d", getpid());
    write(fd, buf, strlen(buf));    

    // close(fd);
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,185评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,652评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,524评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,339评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,387评论 6 391
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,287评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,130评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,985评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,420评论 1 313
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,617评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,779评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,477评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,088评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,716评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,857评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,876评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,700评论 2 354

推荐阅读更多精彩内容

  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,850评论 0 0
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,451评论 0 13
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,791评论 0 38
  • 学习使我们提升了很多能力,具备了很多的能力,我们就一定能把有关的事情做好吗?答案是否定的。因为你所处的时间,空间,...
    颜士民泰安阅读 75评论 0 0
  • QGIS二次开发,调用公网地图,发现闪烁,有时候出现卡死。研究一下发现这是qgis的弊端,这点无法和openlay...
    cgscloud阅读 2,025评论 2 0