Skip to main content

sysprims_session/
lib.rs

1//! GPL-free session and process group management.
2//!
3//! This crate provides cross-platform primitives for session and process group
4//! management, replacing GPL-licensed tools like `setsid` (util-linux) and
5//! `nohup` (coreutils).
6//!
7//! # Provenance
8//!
9//! All implementations are derived from POSIX specifications and BSD/MIT-licensed
10//! references. See `docs/design/sysprims-session-behavioral-comparison.md` for the
11//! full provenance record.
12//!
13//! # Features
14//!
15//! - [`run_setsid`] - Run a command in a new session
16//! - [`run_nohup`] - Run a command immune to SIGHUP
17//! - [`prepare_session_acquisition`] - Prepare a Unix spawn-time session
18//!   acquisition hook and sealed same-spawn receipt
19//!
20//! # Example
21//!
22//! ```no_run
23//! use sysprims_session::{run_setsid, SetsidConfig};
24//!
25//! // Run a command in a new session (detached from terminal)
26//! let result = run_setsid("sleep", &["60"], SetsidConfig::default());
27//! ```
28
29use std::process::ExitStatus;
30use std::{collections::BTreeMap, path::PathBuf};
31use sysprims_core::SysprimsResult;
32
33#[cfg(unix)]
34mod unix;
35
36#[cfg(unix)]
37pub use unix::{
38    prepare_session_acquisition, PendingUnixSessionReceipt, UnixSessionAcquisitionHook,
39    UnixSessionReceipt,
40};
41
42// ============================================================================
43// setsid - Create New Session
44// ============================================================================
45
46/// Configuration for setsid execution.
47#[derive(Debug, Clone, Default)]
48pub struct SetsidConfig {
49    /// Wait for the child process to exit and return its status.
50    ///
51    /// When `false` (default), returns immediately after spawning.
52    /// When `true`, waits for child and returns its exit status.
53    pub wait: bool,
54
55    /// Create a controlling terminal (ctty) for the new session.
56    ///
57    /// This is a no-op placeholder for compatibility with util-linux setsid -c.
58    /// Most use cases don't need this.
59    pub ctty: bool,
60
61    /// Working directory for the child process.
62    ///
63    /// `None` means inherit the caller's current working directory.
64    pub cwd: Option<PathBuf>,
65
66    /// Environment overrides for the child process.
67    ///
68    /// Values are merged into the inherited environment. v1 does not provide a
69    /// replace-or-clear environment mode.
70    pub env: Option<BTreeMap<String, String>>,
71}
72
73/// Outcome of setsid execution.
74#[derive(Debug)]
75pub enum SetsidOutcome {
76    /// Child spawned successfully in new session.
77    ///
78    /// When `wait: false`, the child continues running detached.
79    Spawned {
80        /// PID of the child process in the new session.
81        child_pid: u32,
82    },
83
84    /// Child completed (when `wait: true`).
85    Completed {
86        /// PID of the child process in the new session.
87        child_pid: u32,
88        /// Exit status of the child.
89        exit_status: ExitStatus,
90    },
91}
92
93/// Run a command in a new session.
94///
95/// Creates a new session with the command as session leader, detaching it
96/// from the controlling terminal and parent process group.
97///
98/// This is equivalent to the `setsid` command from util-linux, but GPL-free.
99///
100/// # Arguments
101///
102/// * `command` - Command to execute
103/// * `args` - Command arguments
104/// * `config` - Execution configuration
105///
106/// # Returns
107///
108/// * `Ok(SetsidOutcome::Spawned { .. })` - Child started in new session
109/// * `Ok(SetsidOutcome::Completed { .. })` - Child finished (if `wait: true`)
110/// * `Err(SysprimsError)` - Failed to spawn or setsid failed
111///
112/// # Example
113///
114/// ```no_run
115/// use sysprims_session::{run_setsid, SetsidConfig};
116///
117/// // Spawn detached
118/// let result = run_setsid("sleep", &["300"], SetsidConfig::default())?;
119///
120/// // Wait for completion
121/// let result = run_setsid("make", &["build"], SetsidConfig { wait: true, ..Default::default() })?;
122/// # Ok::<(), sysprims_core::SysprimsError>(())
123/// ```
124pub fn run_setsid(
125    command: &str,
126    args: &[&str],
127    config: SetsidConfig,
128) -> SysprimsResult<SetsidOutcome> {
129    #[cfg(unix)]
130    return unix::run_setsid_impl(command, args, &config);
131
132    #[cfg(windows)]
133    {
134        let _ = (command, args, config); // Unused on Windows
135        return Err(sysprims_core::SysprimsError::not_supported(
136            "setsid", "windows",
137        ));
138    }
139}
140
141// ============================================================================
142// nohup - Ignore SIGHUP
143// ============================================================================
144
145/// Configuration for nohup execution.
146#[derive(Debug, Clone, Default)]
147pub struct NohupConfig {
148    /// File to redirect stdout to when stdout is a terminal.
149    ///
150    /// Default: "nohup.out" in current directory, falls back to $HOME/nohup.out
151    pub output_file: Option<String>,
152
153    /// Wait for the child process to exit.
154    pub wait: bool,
155
156    /// Working directory for the child process.
157    ///
158    /// `None` means inherit the caller's current working directory.
159    pub cwd: Option<PathBuf>,
160
161    /// Environment overrides for the child process.
162    ///
163    /// Values are merged into the inherited environment. v1 does not provide a
164    /// replace-or-clear environment mode.
165    pub env: Option<BTreeMap<String, String>>,
166}
167
168/// Outcome of nohup execution.
169#[derive(Debug)]
170pub enum NohupOutcome {
171    /// Child spawned successfully with SIGHUP ignored.
172    Spawned {
173        /// PID of the child process.
174        child_pid: u32,
175        /// Output file if stdout was redirected.
176        output_file: Option<String>,
177    },
178
179    /// Child completed (when `wait: true`).
180    Completed {
181        /// PID of the child process.
182        child_pid: u32,
183        /// Exit status of the child.
184        exit_status: ExitStatus,
185        /// Output file if stdout/stderr was redirected.
186        output_file: Option<String>,
187    },
188}
189
190/// Run a command immune to SIGHUP.
191///
192/// Sets SIGHUP to be ignored before executing the command, allowing it to
193/// continue running after the terminal is closed.
194///
195/// If stdout is a terminal, output is redirected to `nohup.out`.
196///
197/// This is equivalent to the `nohup` command from coreutils, but GPL-free.
198///
199/// # Arguments
200///
201/// * `command` - Command to execute
202/// * `args` - Command arguments
203/// * `config` - Execution configuration
204///
205/// # Example
206///
207/// ```no_run
208/// use sysprims_session::{run_nohup, NohupConfig};
209///
210/// let result = run_nohup("./long-running-job.sh", &[], NohupConfig::default())?;
211/// # Ok::<(), sysprims_core::SysprimsError>(())
212/// ```
213pub fn run_nohup(
214    command: &str,
215    args: &[&str],
216    config: NohupConfig,
217) -> SysprimsResult<NohupOutcome> {
218    #[cfg(unix)]
219    return unix::run_nohup_impl(command, args, &config);
220
221    #[cfg(windows)]
222    {
223        let _ = (command, args, config); // Unused on Windows
224        return Err(sysprims_core::SysprimsError::not_supported(
225            "nohup", "windows",
226        ));
227    }
228}
229
230// ============================================================================
231// Low-level APIs
232// ============================================================================
233
234/// Create a new session for the current process.
235///
236/// This is a thin wrapper around the `setsid(2)` system call.
237///
238/// # Safety
239///
240/// This must not be called if the current process is a process group leader,
241/// as `setsid()` will fail with EPERM. Fork first if needed.
242///
243/// # Returns
244///
245/// The new session ID (which equals the process ID) on success.
246#[cfg(unix)]
247pub fn setsid() -> SysprimsResult<u32> {
248    unix::setsid_impl()
249}
250
251/// Get the session ID for a process.
252///
253/// # Arguments
254///
255/// * `pid` - Process ID (0 for current process)
256#[cfg(unix)]
257pub fn getsid(pid: u32) -> SysprimsResult<u32> {
258    unix::getsid_impl(pid)
259}
260
261/// Set the process group ID for a process.
262///
263/// # Arguments
264///
265/// * `pid` - Process ID (0 for current process)
266/// * `pgid` - Process group ID (0 to use pid as pgid)
267#[cfg(unix)]
268pub fn setpgid(pid: u32, pgid: u32) -> SysprimsResult<()> {
269    unix::setpgid_impl(pid, pgid)
270}
271
272/// Get the process group ID for a process.
273///
274/// # Arguments
275///
276/// * `pid` - Process ID (0 for current process)
277#[cfg(unix)]
278pub fn getpgid(pid: u32) -> SysprimsResult<u32> {
279    unix::getpgid_impl(pid)
280}
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285
286    #[test]
287    fn setsid_config_defaults() {
288        let config = SetsidConfig::default();
289        assert!(!config.wait);
290        assert!(!config.ctty);
291    }
292
293    #[test]
294    fn nohup_config_defaults() {
295        let config = NohupConfig::default();
296        assert!(config.output_file.is_none());
297        assert!(!config.wait);
298    }
299}