#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int fd,fdsize;
time_t t;
if((pid=fork())<0)//判断创建的子进程是否成功
{
perror("fork");
exit(1);
}
else if(pid>0)
{
exit(0);//父进程退出
}
setsid();//在子进程中建立新会话
chdir("/");//改变当前目录
umask(0);//重设文件权限掩码
fdsize=getdtablesize();//获取当前进程文件描述表大小
for(fd=0;fd<fdsize;fd++)
{
close(fd); //关闭文件描述符
}
while(1)//循环向文件写入当前时间
{
char buf[100];
t=time(NULL);
if((fd=open("/tmp/timeupdate.txt",O_CREAT|O_WRONLY|O_APPEND,0666))<0)
{
perror("open");
exit(1);
}
sprintf(buf,"%s",ctime(&t));//向buf内存缓冲打印时间
write(fd,buf,strlen(buf));//不能使用sizeof
close(fd);
sleep(3);//间隔3秒
}
}
02-02
445