Linux Guard Service - 守护进程的作用、用途、父进程标识的特点

让test2直接成为守护进程

[root@localhost 02]# cat test2.c 
//test2
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<stdlib.h>


int main(){

        if(daemon(1,1)==-1){
                perror("daemon error");
                exit(EXIT_FAILURE);
        }

        int i=0;

        while(1){
                FILE *fd=fopen("test2.log","a");
                fprintf(fd,"%d 1552227\n",i++);
                sleep(1);
                fclose(fd);
        }
        return 0;
}
[root@localhost 02]#

执行test2后生成了test2.log文件,不断更新的test2.log表示其在不断运行

32 1552227
33 1552227
34 1552227
35 1552227
36 1552227
37 1552227
38 1552227
39 1552227
40 1552227
[root@localhost 02]#

退出当前终端,(此时不再提示有进行中的任务)启用新终端,再观察test2.log

37 1552227
38 1552227
39 1552227
40 1552227
41 1552227
42 1552227
43 1552227
44 1552227
[root@localhost 02]# 

发现程序依然在正常执行

使用

ps -xf 

查看所有守护进程

  2761 ?        Sl     0:00  \_ /usr/libexec/evolution-addressbook-factory-subpr
  2766 ?        Sl     0:00 /usr/libexec/ibus-x11 --kill-daemon
  2837 ?        Sl     0:00 /usr/libexec/gvfsd-network --spawner :1.4 /org/gtk/g
  2852 ?        Sl     0:00 /usr/libexec/gvfsd-dnssd --spawner :1.4 /org/gtk/gvf
  9158 ?        Ss     0:00 ./test2
  9187 ?        Sl     0:00 /usr/sbin/abrt-dbus -t133
[root@localhost 02]#

./test2是顶级进程,没有父进程(不同于之前的以-bash作为父进程

在进程中打印信息,可以使用向log输出的方法,但是注意几点

  1. 写文件每次都要close,否则是写不进去的
  2. 要对程序写日志加以控制,否则会产生上GB的文本日志,多个写日志程序同时运行可能会宕机系统
posted @ 2018-03-03 23:48  liutianchen  阅读(2521)  评论(0编辑  收藏  举报