守护进程 linux 实例

代码:

#include <unistd.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <time.h>

void init_daemon(void)
{
    int pid;
    int i;
    //first process
    if (pid=fork())
    {
        exit(0);
    }
    else if(pid < 0)
    {
        printf("forck() error!\n");
        exit(1);
    }
    setsid();
    //second process
    if (pid=fork())
    {
        exit(0);
    }
    else if(pid < 0)
    {
        printf("forck() error!\n");
        exit(1);
    }
    //close file
    for(i=0; i<NOFILE; ++i)
    {
        close(i);
    }
    //change directy
    chdir("/home/hailonxi");
    umask(0);
    return;
}

int main()
{
    FILE *fp;
    time_t t;
    init_daemon();

//This is the operation in the daemon process
    while(1)
    {
        sleep(20);
        if ((fp=fopen("test.log","a")) >= 0){
            t=time(0);
            fprintf(fp,"i am here at %s\n",asctime(localtime(&t)));
            fclose(fp);
            }
        }
}
    

编译&运行:

//查看守护进程

ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ gcc daemon.c
ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ ./a.out
ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ ps -ef | grep a.out
hailonxi 29978     1  0 15:52 ?        00:00:00 ./a.out
hailonxi 29982 11183  0 15:52 pts/9    00:00:00 grep a.out

//守护进程后台运行  ps看不到

ngnsvr9 [** NONE **]/home/xionghailong/unix/file $ ps
  PID TTY          TIME CMD
11183 pts/9    00:00:00 bash
29983 pts/9    00:00:00 ps

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值