Skip to main content

spawn

Function spawn 

Source
pub fn spawn() -> Result<()>
Expand description

Spawns the application as a detached background process.

This function creates a new background process that runs independently of the parent process. It handles platform-specific process creation, PID file management, and ensures only one daemon instance runs at a time.

§Process Management

  1. Existing Process Check: Verifies no daemon is already running
  2. Process Termination: Stops any existing daemon before starting new one
  3. Process Creation: Spawns new daemon with platform-specific flags
  4. PID Recording: Saves the new process ID for future management
  5. Status Reporting: Provides feedback about the spawning operation

§Platform-Specific Spawning

§Unix Systems

std::process::Command::new(current_exe)
    .arg("--daemon-run")
    .pre_exec(|| {
        nix::unistd::setsid()?; // Create new session
        Ok(())
    })
    .spawn()?;

§Windows

std::process::Command::new(current_exe)
    .arg("--daemon-run")
    .creation_flags(CREATE_NO_WINDOW) // Hide console window
    .spawn()?;

§Duplicate Prevention

The function prevents multiple daemon instances by:

  • Checking for existing PID files
  • Validating that the process in the PID file is actually running
  • Terminating stale processes before starting new ones
  • Cleaning up orphaned PID files

§Error Recovery

If stopping an existing daemon fails:

  • Issues a warning but continues with spawning
  • Removes stale PID files to prevent conflicts
  • Allows a brief delay for process cleanup
  • Proceeds with new daemon creation

§Returns

Returns Ok(()) if the daemon was successfully spawned and the PID file was created, or an error if the spawning process fails.

§Error Scenarios

  • Executable Not Found: Cannot locate the current executable
  • Permission Denied: Insufficient privileges for process creation
  • Resource Exhaustion: System cannot create new processes
  • PID File Creation: Cannot write PID file to application directory
  • Platform Unsupported: Daemon mode not available on the current platform

§Usage Examples

use kasl::libs::daemon;

// Start background monitoring
daemon::spawn()?;
println!("Background monitoring started");

§Security Considerations

  • The spawned process runs with the same privileges as the parent
  • PID files are created with user-readable permissions only
  • No sensitive information is passed via command line arguments
  • Process isolation is maintained through session separation (Unix)