-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.c
49 lines (47 loc) · 1.04 KB
/
daemon.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
void init_daemon(void)
{
int pid;
int i;
if(pid=fork())
exit(0);//是父进程,结束父进程
else if(pid< 0)
exit(1);//fork失败,退出
//是第一子进程,后台继续执行
setsid();//第一子进程成为新的会话组长和进程组长
//并与控制终端分离
if(pid=fork())
exit(0);//是第一子进程,结束第一子进程
else if(pid< 0)
exit(1);//fork失败,退出
//是第二子进程,继续
//第二子进程不再是会话组长
#if 0
for(i=0;i< NOFILE;++i)//关闭打开的文件描述符
close(i);
#endif
chdir("/tmp");//改变工作目录到/tmp
umask(0);//重设文件创建掩模
return;
}
int main(){
init_daemon();
FILE *f;
while(1){
f = fopen("log", "a+");
if(f){
time_t t = time(0);
fprintf(f, "Im here at %s", asctime(localtime(&t)));
fclose(f);
}
sleep(10);
}
return 0;
}