#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #include <time.h> void sysErr(const char* err,int status) { perror(err); exit(status); } void deamonize() { pid_t pid; pid = fork(); if (pid > 0) { exit(0); } else if (pid < 0) { sysErr("fork",-1); } setsid();// 子进程创建会话,独立出来,脱离控制 // 改变工作路径、 // if (chdir("/") != 0) // { // sysErr("chdir",errno); // } // 重设文件掩码 umask(0); close(0); open("/dev/null",O_RDWR); dup2(1,0); dup2(2,0); } void writeLog(const char* buf) { int fdLog; fdLog = open("./deamon.log",O_RDWR | O_APPEND | O_CREAT,0644); if (fdLog < 0) { sysErr("open log file failed.",errno); } // 时间 char bufTime[64] = {0}; time_t now_t; time(&now_t); struct tm ptimeT = {0}; localtime_r(&now_t,&ptimeT); sprintf(bufTime,"%04d-%02d-%02d-%02d-%02d-%02d:",ptimeT.tm_year+1900,ptimeT.tm_mon+1,ptimeT.tm_mday, ptimeT.tm_hour,ptimeT.tm_min,ptimeT.tm_sec); write(fdLog,bufTime,strlen(bufTime)); write(fdLog,buf,strlen(buf)); close(fdLog); } int main(int argc, char **argv) { deamonize(); // 守护进程核心工作 while(1) { writeLog("hello\n"); sleep(2); } return 0; }