前一篇内容,对进程的相关内容做了介绍,下面我们可以通过这个练习进行巩固学习,代码写在了下边,可以做一个参考;
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
//1、创建子进程,父进程退出
pid_t pid = fork();
if(pid < 0)
{
perror("fork");
exit(-1);
}
if(pid > 0)
{
exit(0);
}
//2、脱离原本会话
setsid();
//3、修改工作路径
chdir("/tmp");
//4、修改文件权限掩码
umask(0);
//5、关闭所有的文件描述符
int i = 0;
for(i = 0; i < getdtablesize(); i++)
{
close(i);
}
FILE *fp = fopen("time.log", "a+");
if(NULL == fp)
{
perror("fopen");
exit(-1);
}
time_t t;
struct tm *my_t;
while(1)
{
time(&t);
my_t = localtime(&t);
fprintf(fp, "%02d:%02d:%02d\n", my_t->tm_hour, my_t->tm_min,my_t->tm_sec);
fflush(fp);
sleep(1);
}
return 0;
}