zoukankan      html  css  js  c++  java
  • Linux之精灵进程

    一、引言

    工作中有时候可能会写一些这样的程序,它作为后台进程运行,生命周期比一般的进程要长,它在系统开机时运行,直到被强制关闭或者系统关机时退出。它就是精灵进程或者也叫做守护进程--daemon process

    二、写精灵进程的步骤

    1.创建子进程,退出父进程
    2.改变文件的掩码
    3.打开日志文件,以便向里面写入执行信息
    4.创建唯一的会话ID(SID)
    5.改变当前的工作路径到一个安全的地方
    6.关闭标准文件描述符
    7.编写实际的精灵进程代码

    三、实例

    /*******************************************************************************
    * File Name        : daemon.cpp
    * Author        : zjw
    * Email            : zjw_0722@163.com
    * Create Time    : 2015年01月05日 星期一 16时00分15秒
    *******************************************************************************/
    
    #include <unistd.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <time.h>
    #include <stdlib.h>
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main(int argc, char **argv)
    {
        pid_t pid, sid;
        
        // Fork off the parent process
        pid = fork();
        if (pid < 0)
        {
            exit(-1);
        }
    
        // If we got a good PID, then we can exit the parent process.
        if (pid > 0)
        {
            exit(-1);
        }
    
        // Change the file mode mask
        umask(0);
    
        // Open any logs here
        ofstream fout("/var/log/daemon.log");
        if (!fout)
        {
            exit(-1);
        }
    
        // Create a new SID(Session ID) for the child process
        sid = setsid();
        if (sid < 0)
        {
            // Log any failure
            exit(-1);
        }
    
        // Change the current working directory
        if ((chdir("/")) < 0)
        {
            // Log any failure
            exit(-1);
        }
    
        // Close out the standard file descriptors
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
    
        // Daemon-specific initialization goes here
        
        // The big loop
        while (true)
        {
            time_t timeNow;
            time(&timeNow);
            fout << asctime(localtime(&timeNow)) << endl;
    
            sleep(30);
        }
        cout << "over" << endl;        
        return 0;
    }

    这只是一个简单的实例代码,简单的描述了编写精灵进程的大体步骤。其中我遇到了一个这样的问题,运行时出现错误,调试跟踪发现无法打开文件/var/log/daemon.log,明显是权限的问题。使用root用户运行,OK。这里也引出另外一个问题:如何调试fork的子进程?解决办法:Google gdb 多进程即可。

  • 相关阅读:
    XAML学习笔记之Layout(五)——ViewBox
    XAML学习笔记——Layout(三)
    XAML学习笔记——Layout(二)
    XAML学习笔记——Layout(一)
    从0开始搭建SQL Server 2012 AlwaysOn 第三篇(安装数据,配置AlwaysOn)
    从0开始搭建SQL Server 2012 AlwaysOn 第二篇(配置故障转移集群)
    从0开始搭建SQL Server 2012 AlwaysOn 第一篇(AD域与DNS)
    Sql Server 2012 事务复制遇到的问题及解决方式
    Sql Server 2008R2升级 Sql Server 2012 问题
    第一次ACM
  • 原文地址:https://www.cnblogs.com/lit10050528/p/4204024.html
Copyright © 2011-2022 走看看