2016-12-07 7 views
-1

私は、バックスラッシュでプログラムを起動し、そのプログラムのPIDを決定し、パイプの出力をsedにする関数をbashに持っていたいと思います。私はそれらのいずれかを別々に行う方法を知っていますが、すべてを一度に達成する方法はありません。Bash関数:バックグラウンドでプログラムを起動し、PIDとパイプ出力を決定します。

は、私がこれまで持っていることはこれです:

# Start a program in the background 
# 
# Arguments: 
# 1 - Variable in which to "write" the PID 
# 2 - App to execute 
# 3 - Arguments to app 
# 
function start_program_in_background() { 

    RC=$1; shift 

    # Start program in background and determine PID 
    BIN=$1; shift 
    ($BIN [email protected] & echo $! >&3) 3>PID | stdbuf -o0 sed -e 's/a/b/' & 
    # ALTERNATIVE $BIN [email protected] > >(sed ..) & 

    # Write PID to variable given as argument 1 
    PID=$(<PID) 
    # when using ALTERNATIVEPID=$! 
    eval "$RC=$PID" 

    echo "$BIN ---PID---> $PID" 
} 

私はPIDが触発される抽出方法[1]。コメントには2番目の変種があります。機能の上に使用したプログラムを開始するスクリプトを実行するときに、それらの両方は、バックグラウンド・プロセスの出力を示しているが、出力はないときIパイプ

[1] How to get the PID of a process that is piped to another process in Bash?

任意のアイデアは?

+1

質問には関係ありませんが、結果を適切に再引用するには、二重引用符で囲む必要があります。 – Barmar

+0

発信者はPIDで何をしていますか?それがプロセスを殺すなら、 'sed'に何かを送る機会がある前に、プロセスを殺すかもしれません。 – Barmar

+0

今、私は単純に 'sleep 10'を入れてからkillします。しかし、プロセスが物事を出力するのに十分な時間があるはずです。私は 'stdbuf -i0'を使って問題がバッファリングに関連していないことを確認しました。 –

答えて

0

ソリューション:

私は自分自身にこれを有用なコメントのいくつかに感謝を思い付きました。解決策としてマークすることができるように、私はここに実際の解決策を掲載しています。

# Start a program in the background 
# 
# Arguments: 
# 1 - Variable in which to "write" the PID 
# 2 - App to execute 
# 3 - Arguments to app 
# 
function start_program_in_background() { 

    RC=$1; shift 

    # Create a temporary file to store the PID 
    FPID=$(mktemp) 

    # Start program in background and determine PID 
    BIN=$1; shift 
    APP=$(basename $BIN) 
    (stdbuf -o0 $BIN [email protected] 2>&1 & echo $! >&3) 3>$FPID | \ 
      stdbuf -i0 -o0 sed -e "s/^/$APP: /" |\ 
      stdbuf -i0 -o0 tee /tmp/log_${APP} & 

    # Need to sleep a bit to make sure PID is available in file 
    sleep 1 

    # Write PID to variable given as argument 1 
    PID=$(<$FPID) 
    eval "$RC=$PID" 

    rm $FPID # Remove temporary file holding PID 
}