1 // This file is written in D programming language
2 /**
3 *   The example demonstrates how to run vibe.d server
4 *   in daemon mode.
5 *   
6 *   If SIGTERM is received, daemon terminates. If SIGHUP is received,
7 *   daemon prints "Hello World!" message to logg.
8 *
9 *   Copyright: © 2014 Anton Gushcha
10 *   License: Subject to the terms of the MIT license, as written in the included LICENSE file.
11 *   Authors: NCrashed <ncrashed@gmail.com>
12 */
13 module example03;
14 
15 import dlogg.strict;
16 import daemonize.d;
17 
18 // cannot use vibe.d due symbol clash for logging
19 import vibe.core.core;
20 import vibe.core.log : setLogLevel, setLogFile, VibeLogLevel = LogLevel;
21 import vibe.http.server;
22 
23 // Simple daemon description
24 alias daemon = Daemon!(
25     "DaemonizeExample3", // unique name
26     
27     KeyValueList!(
28         Composition!(Signal.Terminate, Signal.Quit, Signal.Shutdown, Signal.Stop), (logger)
29         {
30             logger.logInfo("Exiting...");
31             
32             // No need to force exit here
33             // main will stop after the call 
34             exitEventLoop(true);
35             return true; 
36         },
37         Signal.HangUp, (logger)
38         {
39             logger.logInfo("Hello World!");
40             return true;
41         }
42     ),
43     
44     (logger, shouldExit) {
45         // Default vibe initialization
46         auto settings = new HTTPServerSettings;
47         settings.port = 8080;
48         settings.bindAddresses = ["127.0.0.1"];
49 
50         listenHTTP(settings, &handleRequest);
51 
52         // All exceptions are caught by daemonize
53         return runEventLoop();
54     }
55 );
56 
57 // Vibe handler
58 void handleRequest(HTTPServerRequest req,
59                    HTTPServerResponse res)
60 {
61     res.writeBody("Hello World!", "text/plain");
62 }
63 
64 int main()
65 {
66     // Setting vibe logger 
67     // daemon closes stdout/stderr and vibe logger will crash
68     // if not suppress printing to console
69     version(Windows) enum vibeLogName = "C:\\vibe.log";
70     else enum vibeLogName = "vibe.log";
71 
72     // no stdout/stderr output
73     version(Windows) {}
74     else setLogLevel(VibeLogLevel.none);
75 
76     setLogFile(vibeLogName, VibeLogLevel.info);
77 
78     version(Windows) enum logFileName = "C:\\logfile.log";
79     else enum logFileName = "logfile.log";
80 	
81     auto logger = new shared StrictLogger(logFileName);
82     return buildDaemon!daemon.run(logger); 
83 }