complex/
complex.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//
3// This file is licensed under the MIT license or the Apache License, Version 2.0, at your choice.
4//
5// Copyright 2016 Fedor Gogolev
6// Copyright 2025 Oliver Old
7//
8// Licensed under the Apache License, Version 2.0 (the "License");
9// you may not use this file except in compliance with the License.
10// You may obtain a copy of the License at
11//
12//     http://www.apache.org/licenses/LICENSE-2.0
13//
14// Unless required by applicable law or agreed to in writing, software
15// distributed under the License is distributed on an "AS IS" BASIS,
16// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17// See the License for the specific language governing permissions and
18// limitations under the License.
19
20fn main() {
21    #[cfg(unix)]
22    unix::main();
23}
24
25#[cfg(unix)]
26mod unix {
27    extern crate daemonize2;
28
29    use std::fs::File;
30
31    use self::daemonize2::Daemonize;
32
33    pub fn main() {
34        let stdout = File::create("/tmp/daemon.out").unwrap();
35        let stderr = File::create("/tmp/daemon.err").unwrap();
36
37        // Every method except `new` and `start` is optional. See `Daemonize` documentation for
38        // default behaviour.
39        let mut daemonize = Daemonize::new();
40
41        daemonize = daemonize
42            .pid_file("/tmp/test.pid")
43            .chown_pid_file_user("nobody")
44            .chown_pid_file_group("daemon")
45            .working_directory("/tmp");
46
47        // User and group IDs can be either strings or integers.
48        daemonize = daemonize.user("nobody").group("daemon").group(2);
49
50        // Set umask. `0o027` by default.
51        daemonize = daemonize.umask(0o777);
52
53        // Redirect standard output and standard error.
54        daemonize = daemonize.stdout(stdout).stderr(stderr);
55
56        // Run a final privileged action.
57        let daemonize = daemonize.privileged_action(|| "Executed before drop privileges");
58
59        // Start the daemon.
60        match unsafe { daemonize.start() } {
61            Ok(_) => println!("Success, daemonized"),
62            Err(e) => eprintln!("Error, {}", e),
63        }
64    }
65}