小结:使用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)

最新文章

  1. SQL 数据优化之不建立索引的情况
  2. iOS中assign,copy,retain之间的区别以及weak和strong的区别
  3. [nRF51822] 13、浅谈nRF51822和NRF24LE1/NRF24LU1/NRF24L01经典2.4G模块无线通信配置与流程
  4. 网页百度地图API相关资料
  5. HTML确认密码
  6. LeetCode 604. Design Compressed String Iterator (设计压缩字符迭代器)$
  7. Archlinux无线联网教程
  8. 敏捷测试(5)--基于story的敏捷基础知识
  9. 领域驱动设计和Spring
  10. web安全系列3:http拦截
  11. JavaScript:事件
  12. [Aaronyang紫色博客] 写给自己的WPF4.5-Blend5公开课系列 3 - 再来一发
  13. html5——canvas画布
  14. JavaScript三种弹出框(alert,confirm和prompt)用法举例
  15. Mysql 用户ip访问根据省份查询
  16. 【转】web.xml配置项详解
  17. 使用JFreeChart实现基于Web的柱状图
  18. Prettier来统一代码风格
  19. iOS11新特性之LargeTitle
  20. kaggle CTR预估

热门文章

  1. 【工匠大道】将项目同时托管到Github和Git@OSC
  2. 使用CruiseControl.Net全面实现持续集成
  3. JS字符串反序输出
  4. HTTP慢速DOS(slow http denial of service attack)
  5. [Android]一个干净的架构(翻译)
  6. Runtime相关整理
  7. //build-&gt;//learn-&gt;//publish
  8. MySQL备份还原&mdash;&mdash;mysqldump工具介绍
  9. 再探banana
  10. springmvc学习资料整理