2015-10-17 63 views
0

有沒有穩定方式我可以創建一個子進程掛在後臺並繼承stderr,進出?從我看到的情況來看,創建一個child需要我啓動一個單獨的程序。相反,我想創建一個持續時間長於主進程的子進程,並且只允許我複製stderr以便從中讀取。創建複製主進程的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並以某種方式讀取它,終端恢復程序前運行狀態後,我可以重新打印恐慌信息。

回答

2

我相信這對於一個包裝程序來說更容易,而不是從生鏽程序本身啓動一些東西。這裏有一個如何使用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 

當這個鏽程序中使用:

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

它打印:

Normal program output 

--terminal reset shenanigans-- 

thread '<main>' panicked at 'oops', my_rust_program.rs:3 

我相信你可以創建一個在穩定的生鏽也是如此,但既然你在你的問題中提到了sh,我假設你仍然處於unix環境中,並且shell腳本版本應該更簡單。

+0

這是一個非常有創意的很酷的解決方案,但這個問題涉及到一個庫。在運行之前,我無法將整個庫包裝在腳本中。 –