安全地终止后台进程

安全地终止后台进程

我正在将数据写入父进程中的管道。父进程创建一个后台作业,从管道读取数据并将其写入屏幕和日志文件。
我如何知道何时终止后台作业?wait命令只是永远等待。我不想使用令牌来检测“输出结束”。代码示例:

function log()
{
    if [ -z "$counter" ]; then
        counter=1
    else
        (( ++counter ))
    fi

    if ! [[ -z "$teepid" ]]; then
        # ***** How can I know if it's safe to kill here?
        kill $teepid
    fi
    # Display text-to-be-logged on screen
    #  & write text-to-be-logged to it's corresponding log file
    tee <"$pipe" 1>&4 "${logs_dir}/${counter}_${1// /_}" &
    teepid=$!
}

logs_dir="/path/to/log/dir"

pipe_dir=$(mktemp -d)
pipe="${pipe_dir}/cmds_output"
mkfifo "$pipe"
exec 3<>"$pipe" # link file descriptor (FD) #3 to $pipe for r/w
exec 4<&1   # save value of FD1 to FD4
exec 1>&3   # redirect all output to FD3

log # Logs the following code block
{
    # ... Many bash commands ...
}

log # Logs the following code block
{
    # ... Many bash commands ...
}

if ! [[ -z "$teepid" ]]; then
    # ***** How can I know if it's safe to kill here? Maybe it's still logging
    kill $teepid;
fi

编辑:

我试过:

exec 3>&-
#exec 1>&- # Have tried also uncommenting this row
wait $teepid
exec 3<>"$pipe"
exec 1>&3
kill $teepid

但等待命令仍然挂起...我发现它ps -o pid,ppid,s --pid $teepid显示了进程的状态。我应该指望这一点吗?

答案1

完成后只需关闭管道即可。子进程将到达 EOF 并且应该退出。

相关内容