Linux Linux程序练习十七

小结:使用fputs()向文件写入数据,要想实时看到结果,需要使用fflush清空缓冲区
/*
 * 题目:编写一个守护进程,每隔3秒钟将当前时间写入文件time.log,
 * 要求:不能使用init_daemon系统调用。
 * */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>


void gettime_now(char *ptime)
{
    time_t tdata = 0;
    //获取当前系统时间
    time(&tdata);
    //定义时间结构体变量
    struct tm *eventtime = NULL;
    //将time_t类型转成struct tm指针类型
    eventtime = localtime(&tdata);
    //tm_year表示年份,从1900开始
    int t_year = eventtime->tm_year + 1900;
    //月份,月份从0开始
    int t_mon = eventtime->tm_mon + 1;
    //
    int t_day = eventtime->tm_mday;
    //小时
    int t_hour = eventtime->tm_hour;
    //
    int t_min = eventtime->tm_min;
    //
    int t_sec = eventtime->tm_sec;
    sprintf(ptime, "%d-%d-%d %d:%d:%d
", t_year, t_mon, t_day,
            t_hour, t_min, t_sec);
}

int main(void)
{
    pid_t pid = fork();
    if (pid == -1)
    {
        perror("fork() err");
        return -1;
    }
    if (pid == 0)
    {
        //创建新的会话期
        setsid();
        //设置当前目录为根目录
        chdir("/");
        //设置目录权限
        umask(0);
        close(STDERR_FILENO);
        close(STDIN_FILENO);
        FILE *pfa = NULL;
        pfa = fopen("/home/test/1/time.log", "a");
        if (pfa == NULL)
        {
            perror("fopen() err");
            return -1;
        }
        //每隔3秒
        int seconds = 0;
        while (1)
        {
            seconds = 3;
            do
            {
                seconds = sleep(seconds);
            } while (seconds > 0);
            //获取当前时间
            char timearr[50] = { 0 };
            gettime_now(timearr);
            strcat(timearr," 		打印时间

");
            printf("%s",timearr);
            //写入文件
            fputs(timearr, pfa);
            //刷新缓冲区
            fflush(pfa);
        }
    } else if (pid > 0)
    {
        exit(0);
    }
    return -1;
}
.SUFFIXES:.c .o
CC=gcc
SRCS=hello.c
OBJS=$(SRCS:.c=.o)
EXEC=ser
SRCS1=tec01.c
OBJS1=$(SRCS1:.c=.o)
EXEC1=clt

start:$(OBJS) $(OBJS1)
    $(CC) -o $(EXEC) $(OBJS)
    $(CC) -o $(EXEC1) $(OBJS1)
    @echo "^_^-----OK------^_^"
.c.o:
    $(CC) -Wall -g -o $@ -c $<
clean:
    rm -f $(OBJS)
    rm -f $(EXEC)
原文地址:https://www.cnblogs.com/zhanggaofeng/p/6185131.html