1: #include <stdio.h>
2: #include <sys/types.h>
3: #include <unistd.h>
4: #include <stdlib.h>
5: #include <signal.h>
6: #include <errno.h>
7: #include <string.h>
8: #include <sys/stat.h>
9:
10: /**
11: *
12: * Example shows how to properly become a daemon under Linux.
13: * Becoming a daemon after a template from Stevens Book "Unix Network Programming".
14: * Compile with "gcc -W -Wall -g -o daemon main.cc"
15: */
16: void daemonize()
17: {
18: // fork
19: pid_t pid = fork();
20: if ( pid < 0 )
21: {
22: printf( "Error in fork(): ( %d: %s ).", errno, strerror( errno ) );
23: exit( EXIT_FAILURE );
24: }
25: else if ( pid ) // close parent
26: {
27: exit(EXIT_SUCCESS);
28: }
29:
30: // Child continues
31: setsid(); // become session leader
32: // Ignore some signals
33: signal( SIGHUP, SIG_IGN ); // ignore signal SIGHUP
34: signal( SIGINT, SIG_IGN );
35: signal( SIGWINCH, SIG_IGN );
36:
37: // Child forks again
38: pid = fork();
39: if ( pid < 0 )
40: {
41: printf( "Error in fork(): ( %d: %s ).", errno, strerror( errno ) );
42: exit( EXIT_FAILURE );
43: }
44: else if ( pid ) // close first child
45: {
46: exit(EXIT_SUCCESS);
47: }
48:
49: chdir( "/" ); // change working directory
50: umask(0); // clear file mode creation mask
51:
52: // for( int i = 0; i < 64; ++i ) // close all inherited file descriptors
53: // close(i);
54:
55: close(0); // close stdin
56: }
57:
58: /**
59: * The main programm becomes a daemon and shows that it is the session leader by
60: * printing out the result of the "ps x --forest" command.
61: */
62: int main(void)
63: {
64: daemonize();
65: sleep(1);
66:
67: printf( "\nAFTER FORK: \n");
68: system( "ps x --forest | tail -n 4" );
69:
70: return ( EXIT_SUCCESS );
71: }
72:
73: /*
74: * Here's the output
75:
76: AFTER FORK:
77: 6978 ? S 0:00 ./daemon
78: 6979 ? S 0:00 \_ sh -c ps x --forest | tail -n 4
79: 6980 ? R 0:00 \_ ps x --forest
80: 6981 ? S 0:00 \_ tail -n 4
81: */
82: