rust - 如何在 Rust 中 fork/exec 转发所有参数的进程?

标签 rust process fork exec

我想用 Rust 编写以下内容。我不知道如何使用 Command API 执行此操作。

if [[ -z "${DEPLOY_ENV}" ]]; then
  $old_program "$@"
else
  $new_program "$@"
fi

最佳答案

Command API是跨平台的,并不是所有平台都有execfork的概念。但是,标准库确实提供了 exec()通过 std::os::unix::process::CommandExt 扩展特征在 Unix 平台上执行 Command 的方法。

use std::process::Command;
use std::os::unix::process::CommandExt;

fn main() {
    let args: Vec<_> = std::env::args_os().skip(1).collect();
    let err = Command::new("new_program")
        .args(&args)
        .exec();
    println!("Error: {}", err);
}

或者,您可以使用 fork crate :

use fork::{fork, Fork};

fn main() {
    // keeps the same arguments of course
    match fork() {
       Ok(Fork::Parent(child)) => println!("Continuing execution in parent process, new child has pid: {}", child),
       Ok(Fork::Child) => println!("I'm a new child process"),
       Err(_) => println!("Fork failed"),
    }
}

exec crate :

use exec::Command;

fn main() {
    let args: Vec<_> = std::env::args_os().skip(1).collect();
    let err = Command::new("new_program")
        .args(&args)
        .exec();
    println!("Error: {}", err);
}

或者,如果您愿意,可以更直接地调用 nix 给他们打电话。或libc crate 。

关于rust - 如何在 Rust 中 fork/exec 转发所有参数的进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65969353/

相关文章:

rust - if-let 还是普通 if 条件更好?

rust - 连字符无法识别的 crate 名称

c# - File.Delete 无法删除文件,因为该文件正在被另一个进程使用。不知道如何解决这个问题

python - 检查进程是否作为管道运行

linux - fork: retry: 资源暂时不可用

rust - 为什么 Fn 派生自 FnMut(派生自 FnOnce)?

rust - 使用Arrayfire设置索引值

java - 如何检查某个进程是否正在运行 - Linux 上的 java

c fork pipe 和 read 函数从文件描述符中给出随机字节

c - 将子进程中创建的有效指针地址通过管道传输到父进程