Linux Linux程序练习十七

时间:2023-03-09 00:48:16
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 = ;
//获取当前系统时间
time(&tdata);
//定义时间结构体变量
struct tm *eventtime = NULL;
//将time_t类型转成struct tm指针类型
eventtime = localtime(&tdata);
//tm_year表示年份,从1900开始
int t_year = eventtime->tm_year + ;
//月份,月份从0开始
int t_mon = eventtime->tm_mon + ;
//日
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\n", t_year, t_mon, t_day,
t_hour, t_min, t_sec);
} int main(void)
{
pid_t pid = fork();
if (pid == -)
{
perror("fork() err");
return -;
}
if (pid == )
{
//创建新的会话期
setsid();
//设置当前目录为根目录
chdir("/");
//设置目录权限
umask();
close(STDERR_FILENO);
close(STDIN_FILENO);
FILE *pfa = NULL;
pfa = fopen("/home/test/1/time.log", "a");
if (pfa == NULL)
{
perror("fopen() err");
return -;
}
//每隔3秒
int seconds = ;
while ()
{
seconds = ;
do
{
seconds = sleep(seconds);
} while (seconds > );
//获取当前时间
char timearr[] = { };
gettime_now(timearr);
strcat(timearr," \t\t打印时间\n\n");
printf("%s",timearr);
//写入文件
fputs(timearr, pfa);
//刷新缓冲区
fflush(pfa);
}
} else if (pid > )
{
exit();
}
return -;
}
.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)