关于守护进程的程序无法运行(新手)
为什么我把守护进程和获取时间封装成函数就不能实现?
//实现功能:每隔10s 写 日期时分秒 到log文件中
//
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#define LOG_FILE "log.txt"
#define MODE "a+"
void Daemon()
{
int i;
const int MAXFD = 64;
if(fork() != 0)
{
exit(0);
}
setsid();
chdir("/");
umask(0);
for(i = 0; i < MAXFD; i ++)
{
close(i);
}
}
void GetTime()
{
FILE *fp = fopen(LOG_FILE, MODE);
if(NULL == fp)
{
perror("fopen");
return;
}
char *wday[] = {"Sum", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
time_t timep;
struct tm *p;
time(&timep);
p = localtime(&timep);
fprintf(fp,"%d-%d-%d", (1900 + p->tm_year), (1 + p->tm_mon), p->tm_mday);
fprintf(fp,"%s%d:%d:%d---\n", wday[p->tm_wday], p->tm_hour, p->tm_min, p->tm_sec);
fclose(fp);
}
int main()
{
Daemon();
while(1)
{
GetTime();
sleep(10);
}
return 0;
}
------解决方案--------------------
nanosleep({10, 0}, 0xbffff4c4) = 0
open("./log.txt", O_RDWR|O_CREAT|O_APPEND, 0666) = -1 EACCES (Permission denied)
write(2, "fopen: Permission denied\n", 25) = -1 EBADF (Bad file descriptor)
跟踪发现是open出错了, 权限不足, 原因我想了一下, 发现是因为chdir到/了, 需要root权限, 你用root身份运行就可以了, 或者chdir不要切到/目录, 切一个有权限的目录即可.