Linux Linux程序练习八

题目:自己动手实现一个守护进程,当控制台窗口关闭时还可以在后台运行。
每隔一秒钟向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=0;
    pid=fork();
    if(pid>0)
    {
        exit(0);
    }
    if(pid==0)
    {
        setsid();
        chdir("/");
        umask(0);
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
        int i=0;
        char buf[30]={0};
        while(1)
        {
            sleep(1);
            sprintf(buf,"fly on air %d
",i++);
            writelog("/home/test/1/testlog.txt",buf);
            memset(buf,0,sizeof(buf));
        }
    }
    return 0;
}
#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=0;
    pid=fork();
    if(pid>0)
    {
        exit(0);
    }
    if(pid==0)
    {
        setsid();
        chdir("/");
        umask(0);
        close(STDIN_FILENO);
        close(STDOUT_FILENO);
        close(STDERR_FILENO);
        int i=0;
        char buf[30]={0};
        while(1)
        {
            sleep(1);
            sprintf(buf,"fly on air %d
",i++);
            writelog("/home/test/1/testlog.txt",buf);
            memset(buf,0,sizeof(buf));
        }
    }
    return 0;
}
.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)

 

原文地址:https://www.cnblogs.com/zhanggaofeng/p/5852765.html