题目:自己动手实现一个守护进程,当控制台窗口关闭时还可以在后台运行。
每隔一秒钟向my.log文件中插入一条记录,记录格式如下:yyyy-mm-dd hh:mi:se 记录内容,其中yyyy为年,mm为月,dd为天,hh为小时,mi为分钟, se为秒。
#ifdef __cplusplus
extern "C"
{
#endif
//写日志函数
//path:日志文件名
//msg:日志信息
int writelog(const char *path, const char * msg);
#ifdef __cplusplus
}
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "mylog.h"
int main(int arg,char * args[])
{
pid_t pid=;
pid=fork();
if(pid>)
{
exit();
}
if(pid==)
{
setsid();
chdir("/");
umask();
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
int i=;
char buf[]={};
while()
{
sleep();
sprintf(buf,"fly on air %d\n",i++);
writelog("/home/test/1/testlog.txt",buf);
memset(buf,,sizeof(buf));
}
}
return ;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "mylog.h"
int main(int arg,char * args[])
{
pid_t pid=;
pid=fork();
if(pid>)
{
exit();
}
if(pid==)
{
setsid();
chdir("/");
umask();
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
int i=;
char buf[]={};
while()
{
sleep();
sprintf(buf,"fly on air %d\n",i++);
writelog("/home/test/1/testlog.txt",buf);
memset(buf,,sizeof(buf));
}
}
return ;
}
.SUFFIXES:.c .o
CC=gcc
SRCS=hello.c
OBJS=$(SRCS:.c=.o)
EXEC=tecd
start:$(OBJS)
$(CC) -L. -lmylog -o $(EXEC) $(OBJS)
@echo "^_^-----OK------^_^"
.c.o:
$(CC) -Wall -g -o $@ -c $<
clean:
rm -f $(OBJS)
rm -f $(EXEC)
