zoukankan      html  css  js  c++  java
  • [学习笔记]守护进程深入理解

    什么是守护进程

    q  守护进程是在后台运行不受控端控制的进程,通常情况下守护进程在系统启动时自动运行

    q  守护进程的名称通常以d结尾,比如sshd、xinetd、crond等

    创建守护进程步骤

    q  调用fork(),创建新进程,它会是将来的守护进程

    q  在父进程中调用exit,保证子进程不是进程组组长

    q  调用setsid创建新的会话期

    q  将当前目录改为根目录 (如果把当前目录作为守护进程的目录,当前目录不能被卸载,它作为守护进程的工作目录了。)

    q  将标准输入、标准输出、标准错误重定向到/dev/null

    守护进程api

    int daemon(int nochdir, int noclose);

    q  功能:创建一个守护进程

    q  参数:

    q  nochdir:=0将当前目录更改至“/”

    q  noclose:=0将标准输入、标准输出、标准错误重定向至“/dev/null”

    man setsid

    DESCRIPTION

           setsid() creates a new session if the calling process is not a process group leader.  The calling process is the leader  of the new session, the process group leader of the new process group, and has no controlling tty.  The  process  group   ID  and  session  ID of the calling process are set to the PID of the calling process.  The calling process will be the    only process in this new process group and in this new session.

    有的进程有tty,有的进程没有tty。带问号的是守护进程。

    会话期:是一个或者多个进程组的集合,通常一个会话期开始与用户登录,终止于用户退出。在此期间,该用户运行的所有进程都属于这个会话期。

    #include <unistd.h>
    #include <sys/stat.h>
    #include <sys/wait.h>
    #include <sys/types.h>
    #include <fcntl.h>
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <signal.h>
    
    
    #define ERR_EXIT(m) 
        do 
        { 
            perror(m); 
            exit(EXIT_FAILURE); 
        } while(0)
    
    int setup_daemon(int nochdir, int noclose);
    
    int main(int argc, char *argv[])
    {
        mydaemon(1, 1);
        //man daemon 可以看到
        //0表示改变重定向   1表示不改变
        //daemon(1, 1);
        printf("test ...
    ");
        for (;;) ;
        return 0;
    }
    
    int mydaemon(int nochdir, int noclose)
    {
        pid_t pid;
        pid = fork();
        if (pid == -1)
            ERR_EXIT("fork error");
    
        if (pid > 0)
            exit(EXIT_SUCCESS);
    
        setsid();
        
        
        if (nochdir == 0)
            chdir("/");
        
        if (noclose == 0)
        {
            int i;
            for (i=0; i<3; ++i)
                close(i);
            open("/dev/null", O_RDWR);  //把守护进程 的标准输出关联到 进程的0号fd文件描述符上 
            //复制0文件描述符给一个空闲的文件描述符
            dup(0); //标准输出 也指向/dev/null  //    dup2(0, 1);
        
            dup(0); //标准错误输出,也指向/dev/null //    dup2(0, 2);
        }
        return 0;
        
    }

    图片来自敬爱的老师:王保明

  • 相关阅读:
    常用的SQL语句
    解决Pycharm中module 'pip' has no attribute 'main'的问题
    [转]如何使用Fiddler抓取指定浏览器的数据包
    Linux常用命令
    Android:JACK编译错误汇总及解决
    Linux学习:使用 procrank 测量系统内存使用情况
    Android:动态库(.so)调试技巧
    Android 显示系统:Vsync机制
    Android:cmake开发指南
    Android:高通平台性能调试
  • 原文地址:https://www.cnblogs.com/shichuan/p/4432571.html
Copyright © 2011-2022 走看看