【问题标题】:Create child process that duplicates stderr of main process创建复制主进程的stderr的子进程
【发布时间】:2015-10-17 00:41:30
【问题描述】:

有没有一种稳定的方法可以创建一个在后台挂起并继承stderr、进出的子进程?据我所知,创建child 需要我启动一个单独的程序。相反,我想创建一个与主进程一样长的子进程,并且只允许我复制 stderr 以便我可以从中读取。

这是在链接中创建进程的示例

use std::process::Command;

let output = Command::new("sh")
                     .arg("-c")
                     .arg("echo hello")
                     .output()
                     .unwrap_or_else(|e| { panic!("failed to execute process: {}", e) });
let hello = output.stdout;

喜欢做什么

use std::process::Command;

let leech = Command::new() // create process that hangs out in the background and inherits stderr, stdin and stdout from main process

// ....

// panic occurs somewhere in the program
if thread::panicking {
    output = leech.output().stderr();
}
// screen clears

// print stderr of output

我需要创建各种类型的水蛭,因为显示在主屏幕上的恐慌会因终端图形而被刷新。该库将清除在此过程中清除恐慌消息的屏幕,如果我能够复制 stderr 并以某种方式阅读它,我可以在终端恢复预程序运行状态后重新打印恐慌消息。

【问题讨论】:

    标签: rust


    【解决方案1】:

    我相信使用包装程序更容易做到这一点,而不是从 rust 程序本身启动某些东西。下面是一个如何使用 shell 脚本的示例:

    #!/bin/bash
    
    # Redirection magic from http://stackoverflow.com/a/6317938/667984
    { errors=$(./my_rust_program 2>&1 1>&$original_out); } {original_out}>&1
    
    if [[ $? -ne 0 ]]; then
      echo
      echo "--terminal reset shenanigans--"
      echo
      echo "$errors" >&2
    fi
    

    当与这个 rust 程序一起使用时:

    fn main() {
        println!("Normal program output");
        panic!("oops");
    }
    

    打印出来:

    Normal program output
    
    --terminal reset shenanigans--
    
    thread '<main>' panicked at 'oops', my_rust_program.rs:3
    

    我相信您也可以在稳定的 rust 中创建一个,但由于您在问题中提到 sh,我假设您无论如何都处于 unix 环境中,并且 shell 脚本版本应该更简单。

    【讨论】:

    • 这是一个非常有创意的很酷的解决方案,但这个问题与图书馆有关。我无法在运行之前将整个库包装在脚本中:( .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 2021-10-01
    相关资源
    最近更新 更多