self_cmd 0.1.6

Self-executing command builder for Rust programs / Rust 程序自执行命令构建器
Documentation
[English]#en | [中文]#zh

---

<a id="en"></a>

# 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.

---

## About

This project is an open-source component of [js0.site ⋅ Refactoring the Internet Plan](https://js0.site).

We are redefining the development paradigm of the Internet in a componentized way. Welcome to follow us:

* [Google Group]https://groups.google.com/g/js0-site
* [js0site.bsky.social]https://bsky.app/profile/js0site.bsky.social

---

<a id="zh"></a>

# self_cmd: 自执行命令构建器

- [概述]#概述
- [功能特性]#功能特性
- [使用方法]#使用方法
- [设计理念]#设计理念
- [技术栈]#技术栈
- [项目结构]#项目结构
- [API 参考]#api-参考
- [历史背景]#历史背景

## 概述

`self_cmd` 是 Rust 库,用于创建重新执行当前程序的 Command 实例,保持相同参数和标准输入输出继承。使程序能够生成自身的子进程,同时维持原始执行上下文。

## 功能特性

- **自我复制**: 生成执行当前程序的 Command 对象
- **参数保持**: 自动捕获并转发命令行参数
- **标准输入输出继承**: 维持 stdin、stdout、stderr 连接
- **零依赖**: 仅使用标准库的轻量级实现
- **错误处理**: 基于 Result 的错误传播机制

## 使用方法

添加到 `Cargo.toml`:

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

基本用法:

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

fn main() -> std::io::Result<()> {
    // 创建重新执行此程序的命令
    let mut cmd = self_cmd::get()?;
    
    // 执行命令
    let status = cmd.status()?;
    println!("子进程退出状态: {status}");
    
    Ok(())
}
```

高级用法与自定义处理:

```rust
use self_cmd;

fn restart_self() -> std::io::Result<()> {
    let mut cmd = self_cmd::get()?;
    
    // 命令默认继承标准输入输出
    // 可根据需要进行修改
    cmd.spawn()?;
    
    Ok(())
}
```

## 设计理念

库采用极简主义方法,通过单个公共函数封装自执行的复杂性:

```mermaid
graph TD
    A[程序启动] --> 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[配置标准输入输出继承]
    G --> H[返回 Command]
    H --> I[执行命令]
```

设计确保:
- **简洁性**: 单函数接口
- **可靠性**: 无恐慌的错误处理
- **灵活性**: 返回 Command 供进一步定制
- **性能**: 惰性求值的最小开销

## 技术栈

- **语言**: Rust 2024 版本
- **依赖**: 仅标准库
- **错误处理**: `std::io::Result` 用于 I/O 操作
- **进程管理**: `std::process::Command`
- **环境访问**: `std::env` 获取可执行文件路径和参数

## 项目结构

```
self_cmd/
├── src/
│   └── lib.rs          # 核心实现
├── tests/
│   └── main.rs         # 集成测试
├── readme/
│   ├── en.md          # 英文文档
│   └── zh.md          # 中文文档
├── Cargo.toml         # 项目配置
└── test.sh           # 测试运行脚本
```

## API 参考

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

创建配置为重新执行当前程序的 Command 实例。

**返回值:**
- `Ok(Command)`: 配置好的命令,可直接执行
- `Err(std::io::Error)`: 无法确定当前可执行文件路径时

**行为:**
- 通过 `env::current_exe()` 捕获当前可执行文件路径
- 保留除程序名外的所有命令行参数
- 配置标准输入输出继承 (stdin, stdout, stderr)
- 返回 Command 供执行前进一步定制

**示例:**
```rust
match self_cmd::get() {
    Ok(mut cmd) => {
        // 命令已准备就绪
        cmd.status()?;
    }
    Err(e) => {
        eprintln!("创建自执行命令失败: {e}");
    }
}
```

## 历史背景

自执行程序的概念在计算机科学中根深蒂固,可追溯到早期 Unix 系统,当时程序需要重启自身以重新加载配置或更新。Unix 中的 `exec` 系统调用族为进程替换提供了基础,而 Rust 等现代语言将其抽象为更安全、更符合人体工程学的 API。

自复制模式在以下场景中变得尤为重要:
- **守护进程管理**: 配置更改后需要重启的服务
- **热重载**: 自动重建和重启的开发工具
- **进程监督**: 监控和重启子进程的程序
- **引导程序**: 以提升权限重新执行的安装脚本

Rust 生态系统对内存安全和显式错误处理的重视,使其特别适合实现可靠的自执行模式,避免了传统基于 C 的方法中进程管理经常导致资源泄漏或僵尸进程的陷阱。

---

## 关于

本项目为 [js0.site ⋅ 重构互联网计划](https://js0.site) 的开源组件。

我们正在以组件化的方式重新定义互联网的开发范式,欢迎关注:

* [谷歌邮件列表]https://groups.google.com/g/js0-site
* [js0site.bsky.social]https://bsky.app/profile/js0site.bsky.social