# self_cmd: Self-Executing Command Builder

- [Overview](#overview)
- [Features](#features)
- [Usage](#usage)
- [Design Philosophy](#design-philosophy)
- [Technical Stack](#technical-stack)
- [Project Structure](#project-structure)
- [API Reference](#api-reference)
- [Historical Context](#historical-context)

## Overview

`self_cmd` is a Rust library that creates Command instances for re-executing the current program with identical arguments and stdio inheritance. This enables programs to spawn themselves as child processes while maintaining the original execution context.

## Features

- **Self-Replication**: Generate Command objects that execute the current program
- **Argument Preservation**: Automatically captures and forwards command-line arguments
- **Stdio Inheritance**: Maintains stdin, stdout, and stderr connections
- **Zero Dependencies**: Lightweight implementation using only standard library
- **Error Handling**: Proper Result-based error propagation

## Usage

Add to your `Cargo.toml`:

```toml
[dependencies]
self_cmd = "0.1.0"
```

Basic usage:

```rust
use self_cmd;
use std::process::Command;

fn main() -> std::io::Result<()> {
    // Create a command that will re-execute this program
    let mut cmd = self_cmd::get()?;
    
    // Execute the command
    let status = cmd.status()?;
    println!("Child process exited with: {status}");
    
    Ok(())
}
```

Advanced usage with custom handling:

```rust
use self_cmd;

fn restart_self() -> std::io::Result<()> {
    let mut cmd = self_cmd::get()?;
    
    // The command inherits stdio by default
    // You can modify it if needed
    cmd.spawn()?;
    
    Ok(())
}
```

## Design Philosophy

The library follows a minimalist approach with a single public function that encapsulates the complexity of self-execution:

```mermaid
graph TD
    A[Program Start] --> B["self_cmd::get()"]
    B --> C["env::current_exe()"]
    C --> D["env::args().skip(1)"]
    D --> E["Command::new(program)"]
    E --> F["cmd.args(args)"]
    F --> G[Configure Stdio Inheritance]
    G --> H[Return Command]
    H --> I[Execute Command]
```

The design ensures:
- **Simplicity**: Single function interface
- **Reliability**: Proper error handling without panics
- **Flexibility**: Returns Command for further customization
- **Performance**: Minimal overhead with lazy evaluation

## Technical Stack

- **Language**: Rust 2024 Edition
- **Dependencies**: Standard library only
- **Error Handling**: `std::io::Result` for I/O operations
- **Process Management**: `std::process::Command`
- **Environment Access**: `std::env` for executable path and arguments

## Project Structure

```
self_cmd/
├── src/
│   └── lib.rs          # Core implementation
├── tests/
│   └── main.rs         # Integration tests
├── readme/
│   ├── en.md          # English documentation
│   └── zh.md          # Chinese documentation
├── Cargo.toml         # Project configuration
└── test.sh           # Test runner script
```

## API Reference

### `get() -> std::io::Result<Command>`

Creates a Command instance configured to re-execute the current program.

**Returns:**
- `Ok(Command)`: Configured command ready for execution
- `Err(std::io::Error)`: If unable to determine current executable path

**Behavior:**
- Captures current executable path via `env::current_exe()`
- Preserves all command-line arguments except program name
- Configures stdio inheritance (stdin, stdout, stderr)
- Returns Command for further customization before execution

**Example:**
```rust
match self_cmd::get() {
    Ok(mut cmd) => {
        // Command is ready to use
        cmd.status()?;
    }
    Err(e) => {
        eprintln!("Failed to create self command: {e}");
    }
}
```

## Historical Context

The concept of self-executing programs has deep roots in computer science, dating back to early Unix systems where programs needed to restart themselves for configuration reloads or updates. The `exec` family of system calls in Unix provided the foundation for process replacement, while modern languages like Rust have abstracted this into safer, more ergonomic APIs.

Self-replication patterns became particularly important in:
- **Daemon Management**: Services that need to restart after configuration changes
- **Hot Reloading**: Development tools that rebuild and restart automatically  
- **Process Supervision**: Programs that monitor and restart child processes
- **Bootstrapping**: Installation scripts that re-execute with elevated privileges

The Rust ecosystem's emphasis on memory safety and explicit error handling makes it particularly well-suited for implementing reliable self-execution patterns, avoiding the pitfalls of traditional C-based approaches where process management often led to resource leaks or zombie processes.