• Linux下守护进程


    以下内容仅作为个人记录的参考,但也欢迎读者前来指正。

    创建守护进程有一定流程。

    1.创建子进程,退出父进程。

    pid = fork();
    if(pid>0)
    {
        exit(0);
    }

    2.在子进程中创建新会话。

    关键词:进程组、会话期

    使用setsid()

    #include<sys/types.h>
    #include<unistd.h>
    
    pid_t setsid(void)
    
    -1:出错。
    否则:返回该进程组id

    3.改变当前目录为根目录。

    使用chdir()

    4.重设文件权限掩码

    常用umask(0)

    5.关闭文件描述符

    (i=0;i<MAXFILE;i++)
    {
        close(i);
    }

    代码:

     1 #include<stdio.h>
     2 #include<stdlib.h>
     3 #include<string.h>
     4 #include<fcntl.h>
     5 #include<sys/types.h>
     6 #include<unistd.h>
     7 #include<sys/wait.h>
     8 
     9 int main()
    10 {
    11         pid_t pid;
    12         int i,fd;
    13         char* buf = "this is a daemon.
    ";
    14 
    15         pid = fork();
    16         if(pid<0)
    17         {
    18                 printf("error fork.
    ");
    19                 exit(1);
    20         }
    21         else if(pid>0)
    22         {
    23                 printf("child id is %d.
    ",pid);
    24                 exit(0);
    25         }
    26         setsid();
    27         chdir("/");
    28         umask(0);
    29         for(i=0;i<getdtablesize();i++)
    30         {
    31                 close(i);
    32         }
    33         while(1)
    34         {
    35                 if((fd=open("/tmp/mydaemon.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0)
    36                 {
    37                         printf("create file error.
    ");
    38                         exit(1);
    39                 }
    40                 write(fd,buf,strlen(buf+1));
    41                 close(fd);
    42                 sleep(10);
    43         }
    44         exit(0);
    45 }

    过一段时间,看下内容。

     不知道为啥,换行符没有效果。

     知道了进程id,结束即可。

  • 相关阅读:
    vue项目中echarts使用渐变效果报错echarts is not defined
    vue cli 项目中设置背景图
    vue项目中使用echarts地图
    vue Echarts自适应浏览器窗口大小
    promise函数
    vue中路由传参的方式
    嵌套路由
    PHP——实验三 PHP表单交互
    PHP实验——实验二 php基本程序设计
    Ubuntu系统下安装完成tomcat进入管理页面
  • 原文地址:https://www.cnblogs.com/dayq/p/15362554.html
Copyright © 2020-2023  润新知