#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
int init_daemon(void) {
pid_t pid;
int i;
FILE *fp;
time_t mytime;
pid = fork();
if (pid == -1) {
return -1;
} else if (pid > 0) {
exit(0);
}
else {
setsid();//創建新的會話空間
chdir("/tmp");
umask(0);
for (i = 0; i < getdtablesize(); ++i)
{
close(i);
}
while (1) {
sleep(2);
if ((fp = fopen("test.log", "a")) != NULL)
{
mytime = time(0);
fprintf(fp, "I'm here at %s \n", asctime(localtime(&mytime)));
fclose(fp);
}
}
return 0;
}
}
int main(void) {
init_daemon();
return 0;
}