-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeamon.c
67 lines (55 loc) · 1007 Bytes
/
deamon.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* a simple code for deamon a process
* more info couold refenrece to :
* http://www.cnblogs.com/mickole/p/3188321.html
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#define oops(msg) {perror(msg);exit(0);}
void create_deamon(void);
int main(void)
{
time_t t;
int fd;
create_deamon();
while(1){
fd=open("deamon.log",O_WRONLY|O_CREAT|O_APPEND,0644);
if(fd<0){
oops("open deamon.log");
}
t=time(0);
char*buf=asctime(localtime(&t));
write(fd,buf,strlen(buf));
close(fd);
sleep(5);
}
}
void create_deamon(void)
{
pid_t pid;
pid=fork();
if(pid<0)
oops("fork");
if(pid>0)
exit(0);
//now only one process
if(setsid()<0)
oops("setsid");
//chdir("/"); //whatever you want to change to ,or not
int i;
for(i=0;i<3;i++){
close(i);
/*
fd=open("/dev/null",O_RDWR);
fd=dup(0);
fd=dup(0);
*/
}
umask(0);
return ;
}