systemd_connector/
lib.rs

1//! Systemd integration library
2//!
3//! This library provides a set of utilities for interacting with systemd from Rust.
4//!
5//! It eschews the use of libsystemd bindings in favor of using the `systemctl` command line utility
6//! and environment variables to interact with systemd.
7
8#[cfg(feature = "notify")]
9pub mod notify;
10pub mod properties;
11pub mod socket;
12
13pub use self::socket::sockets;
14pub use self::socket::SystemDSocket;
15
16/// Check if the current process is running under systemd as a service with the given unit name
17pub fn is_systemd(unit: &str) -> bool {
18    if let Ok(properties) = self::properties::properties(unit) {
19        let systemd_pid = properties.property("MainPID");
20        let process_pid = std::process::id().to_string();
21
22        tracing::trace!(
23            MainPID = ?systemd_pid,
24            SelfPID = ?process_pid,
25            "Systemd detected, checking for PID match"
26        );
27
28        return systemd_pid == Some(&process_pid);
29    }
30
31    // If we can't read the properties, we're not running under systemd
32    false
33}
34
35#[cfg(test)]
36mod tests {
37    use super::*;
38
39    #[test]
40    fn test_is_systemd() {
41        assert!(
42            !is_systemd("automoton.service"),
43            "Tests should not be running under the automoton.service systemd unit"
44        );
45    }
46}