题目:自己动手实现一个守护进程,当控制台窗口关闭时还可以在后台运行。
每隔一秒钟向my.log文件中插入一条记录,记录格式如下:yyyy-mm-dd hh:mi:se 记录内容,其中yyyy为年,mm为月,dd为天,hh为小时,mi为分钟, se为秒。
//writelog.c 多进程文件锁互斥写文件
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
int writelog(char * path,char* buf)
{
struct flock sflock;
int fd;
int ret;
fd = open(path,O_WRONLY|O_CREAT | O_APPEND,0666);
if(fd < 0)
{
printf("writelog open =%d",errno);
return -1;
}
printf("open file success\n");
sflock.l_type = F_WRLCK;
sflock.l_start = 0;
sflock.l_whence = SEEK_SET;
sflock.l_len = 0;
sflock.l_pid = getpid();
ret = fcntl(fd,F_SETLK,&sflock);
printf("fcntl lock ret=%d",ret);
if(ret < 0)
{
printf("writelog fcntl error=%d",errno);
return -1;
}
printf("lock file success\n");
write(fd,buf,strlen(buf));
// sleep(5);
getchar();
printf("write data over\n");
sflock.l_type = F_UNLCK;
ret = fcntl(fd,F_SETLK,&sflock);
if(ret < 0)
{
printf("writelog fcntl unlck error=%d",errno);
return -1;
}
close(fd);
}
/*
int main(int argc,char *argv[])
{
writelog("./logtest","hello dxc\n");
}
*/
//writelog.h
#ifndef __WRITE_LOG__
#define __WRITE_LOG__
#ifdef __cplusplus
extern "C"
{
#endif
extern int writelog(char*path,char *buf);
#ifdef __cplusplus
}
#endif
#endif
//daemon.c 守护进程写内容到文件
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include "./writelog.h"
#include <string.h>
#include <time.h>
int main(int argc,char *argv[])
{
char buf[100];
pid_t pid;
int i = 0;
int ret;
time_t stime;
struct tm *pdaytime;
pid = fork();
if(pid < 0)
{
perror("fork");
exit(1);
}
else if(pid > 0)
{
exit(1);
}
else
{//child process
printf("child process pid=%d\n",getpid());
pid = setsid();
if(pid < 0)
{
perror("setsid");
exit(1);
}
printf("setsid ret=%d\n",pid);
ret = chdir("/");
if(ret < 0)
{
perror("chdir");
exit(1);
}
umask(0);
for(i = 0; i < 3;i++)
{
close(i);
}
while(1)
{
memset(buf,0,sizeof(buf));
stime = time(NULL);
pdaytime = gmtime(&stime);
ret = sprintf(buf,"year=%d,mon=%d,day=%d,hou=%d,min=%d,sec=%d\n",pdaytime->tm_year,pdaytime->tm_mon,pdaytime->tm_mday,pdaytime->tm_hour,pdaytime->tm_min,pdaytime->tm_sec);
sprintf(&buf[ret],"i'm daemon process write:%d\n",i);
writelog("home/book/watchman/logtest",buf);
sleep(1);
i++;
}
}
}