Bash功能:在后台启动程序,确定PID和管道输出

时间:2016-12-07 20:16:25

标签: bash background pipe pid

我想在bash中有一个函数,它在后台启动一个程序,确定该程序的PID,并将其输出管道传递给sed。我知道如何分别做其中任何一个,但不知道如何一次完成所有这些。

到目前为止我所拥有的是:

# 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 $@ & echo $! >&3 ) 3>PID | stdbuf -o0 sed -e 's/a/b/' &
    # ALTERNATIVE $BIN $@ > >( sed .. ) &

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

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

我提取PID的方式受[1]的启发。评论中有第二个变体。当执行使用上述函数启动程序的脚本时,它们都显示后台进程的输出,但是当我管道时没有输出

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

解决方案:

我自己想出了一些有用的评论。为了能够标记为已解决,我在此处发布了工作解决方案。

# 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 $@ 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
}