#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/stat.h>
void init_daemon(void);
int main()
{
FILE *fp;
time_t t;
init_daemon();
while (1) {
sleep(10);
if ((fp = fopen("daemonlog.txt", "a+")) >= 0) {
t = time(0);
fprintf(fp, "daemon is running, time of now is %s",asctime(localtime(&t)));
fclose(fp);
}
}
return 1;
}
void init_daemon()
{
pid_t pid;
int i;
pid = fork();
if (pid > 0) {
exit(0);
} else if (pid < 0) {
perror("failed to create child thread!\n");
exit(1);
} else if (pid == 0) {
setsid();
chdir("/tmp");
umask(0);
for (i = 0; i < NOFILE; i++)
close(i);
}
return;
}
daemon程序示例
最新推荐文章于 2024-05-24 10:01:32 发布