码迷,mamicode.com
首页 > 系统相关 > 详细

进程编程:守护进程(daemon)

时间:2017-03-19 16:06:22      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:ret   pre   umask   erro   while   close   src   class   clu   

技术分享

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/stat.h>
#define MAXFILE 65535
int main(){
    pid_t pc;
    int i,fd,len;
    char *buf = "this is a Daemon\n";
    len = strlen(buf);
    pc = fork(); /*第一步*/
    if(pc<0){
        printf("error fork\n");
        exit(1);
    }else if(pc>0){
        exit(0);
    }
    setsid(); /*第二步*/
    chdir("/"); /*第三步*/
    umask(0); /*第四步*/
    for(i=0;i<MAXFILE;i++) /*第五步*/
        close(i);
    while(1){
        if((fd=open("/tmp/daemon5.log",O_CREAT|O_WRONLY|O_APPEND,0600))<0){
            perror("open");
            exit(1);
        }
        write(fd,buf,len);
        close(fd);
        sleep(10);
    }
    return 0;
}

进程编程:守护进程(daemon)

标签:ret   pre   umask   erro   while   close   src   class   clu   

原文地址:http://www.cnblogs.com/ducong/p/6580339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!