【问题标题】:Bash function: start program in background, determine PID and pipe outputBash功能:后台启动程序,确定PID和管道输出
【发布时间】:2016-12-07 20:16:25
【问题描述】:

我想在 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] 的启发。 cmets 中有第二个变体。当执行使用上述函数启动程序的脚本时,它们都显示了后台进程的输出,但是当我管道时没有输出

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

有什么想法吗?

【问题讨论】:

  • 与问题无关,但您应该将$@ 放在双引号中以正确重新引用结果。
  • 调用者对 PID 做了什么?如果它终止进程,它可能会在有机会向sed 发送任何内容之前终止它。
  • 现在,我只是在后面加上一个sleep 10 然后杀死它,是的。但是这个过程应该有足够的时间来输出东西。我还尝试使用stdbuf -i0 来确保问题与缓冲无关。
  • 感谢双引号的提示!
  • 您可能需要在$BIN 上使用stdbuf -o0 以防止其输出到管道被缓冲。

标签: bash background pipe pid


【解决方案1】:

解决方案:

感谢一些有用的 cmets,我自己想出了这个。为了能够标记为已解决,我在此处发布了可行的解决方案。

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

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    相关资源
    最近更新 更多