Listing 1 The main() function
1: #include <stdio.h>
2: #include <unistd.h>
3:
4: /* These files are listed later in this article: */
5: #include "lst03.c"
6: #include "lst02.c"
7:
8: int main()
9: {
10: /* The variable pid will hold the pid returned by fork(). */
11: int pid;
12:
13: /* Use fork() to create an exact copy of this process: */
14: pid = fork();
15:
16: /* If fork() return -1, something went wrong. */
17: if( pid == -1 )
18: {
19: /* Output the error to STDOUT: */
20: perror( "fork error" );
21: /* And exit: */
22: exit(1);
23: }
24:
25: /*
26: * If fork() returned 0, we're in the child. By using
27: * the child, we make sure we're not a process group
28: * leader, and that we're disconnected from the controlling
29: * terminal.
30: */
31: if( pid == 0 )
32: {
33: /*
34: * We use setsid() to create a new session, this works
35: * only if the process is not a process group leader.
36: * Since we're executing in the child here, and a child-
37: * process can never be a process group leader, we can
38: * be sure setsid() will be successful:
39: */
40: setsid();
41:
42: /*
43: * Here, we close STDIN, STDOUT and STERR. The whole idea
44: * with daemons is that they should just lay in the back-
45: * ground doing their job, without making any noise. So,
46: * this daemon will not read nor write any information from
47: * or to the terminal.
48: */
49: close( STDIN_FILENO );
50: close( STDOUT_FILENO );
51: close( STDERR_FILENO );
52:
53: /*
54: * Next thing we do is to change the working directory
55: * to /. This is to make sure the daemon is not making
56: * any device busy that you might want to unmount.
57: */
58: chdir( "/" );
59:
60: /*
61: * So, we've finally become a daemon, so we're ready to
62: * start the infinite-loop:
63: */
64: while(1)
65: {
66: /* This function will take care of all the quota-stuff: */
67: do_quota_stuff();
68:
69: /*
70: * Sleep for a couple of seconds before we perform all
71: * quota-stuff again:
72: */
73: sleep(2);
74: }
75: }
76:
77: /* Everything went fine, so we'll return 0: */
78: return 0;
79: }
|