/docs/MyDocs

To get this branch, use:
bzr branch http://darksoft.org/webbzr/docs/MyDocs

« back to all changes in this revision

Viewing changes to Development/languages/C/Samples/daemon.c

  • Committer: Suren A. Chilingaryan
  • Date: 2009-04-09 03:21:08 UTC
  • Revision ID: csa@dside.dyndns.org-20090409032108-w4edamdh4adrgdu3
import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include <stdio.h>
 
2
  #include <stdlib.h>
 
3
  #include <ctype.h>
 
4
  #include <unistd.h>
 
5
  #include <fcntl.h>
 
6
  #include <signal.h>
 
7
  #include <sys/wait.h>
 
8
 
 
9
  /* Global variables */
 
10
  volatile sig_atomic_t keep_going = 1; /* controls program termination */
 
11
 
 
12
  /* Function prototypes: */
 
13
  void termination_handler (int signum); /* clean up before termination */
 
14
 
 
15
  int
 
16
  main (void)
 
17
  {
 
18
    ...
 
19
 
 
20
    if (chdir (HOME_DIR))         /* change to directory containing data
 
21
                                      files */
 
22
     {
 
23
       fprintf (stderr, "%s': ", HOME_DIR);
 
24
       perror (NULL);
 
25
       exit (1);
 
26
     }
 
27
 
 
28
     /* Become a daemon: */
 
29
     switch (fork ())
 
30
       {
 
31
       case -1:                    /* can't fork */
 
32
         perror ("fork()");
 
33
         exit (3);
 
34
       case 0:                     /* child, process becomes a daemon: */
 
35
         close (STDIN_FILENO);
 
36
         close (STDOUT_FILENO);
 
37
         close (STDERR_FILENO);
 
38
         if (setsid () == -1)      /* request a new session (job control) */
 
39
           {
 
40
             exit (4);
 
41
           }
 
42
         break;
 
43
       default:                    /* parent returns to calling process: */
 
44
         return 0;
 
45
       }
 
46
 
 
47
     /* Establish signal handler to clean up before termination: */
 
48
     if (signal (SIGTERM, termination_handler) == SIG_IGN)
 
49
       signal (SIGTERM, SIG_IGN);
 
50
     signal (SIGINT, SIG_IGN);
 
51
     signal (SIGHUP, SIG_IGN);
 
52
 
 
53
     /* Main program loop */
 
54
     while (keep_going)
 
55
       {
 
56
         ...
 
57
       }
 
58
     return 0;
 
59
  }
 
60
 
 
61
  void
 
62
  termination_handler (int signum)
 
63
  {
 
64
    keep_going = 0;
 
65
    signal (signum, termination_handler);
 
66
  }
 
67