0

我的目标是在不创建任何管道的情况下监视子进程,同时仍然能够区分标准错误和标准输出,并能够检索退出代码。我想避免使用命名管道或 /dev/shm,因为在 SIGKILL 的情况下它们不会被清理(是的,我有很好的和机智的用户)

4

1 回答 1

0

在stackoverflow上挑选了一些想法之后,我想到了这个。不确定这是最聪明的方法,请随时纠正/增强!

% monitor "echo stdout:" "echo stderr:" /bin/bash -c "echo FOO;BAR"
stdout: FOO
stderr: /bin/bash: BAR: command not found
% echo Exit-code: $?
Exit-code: 127

有改进的余地,因为它不断产生 2 个子进程,我怀疑每个重定向 1 个。

#
# PURPOSE 
#   redirect stdout and stderr to 2 distinct functions and retrieve exit code
#
# USAGE 
#   monitor HANDLER_OUT HANDLER_ERR COMMAND ...
#   HANDLER_OUT and HANDLER_ERR can be commands or functions
#   COMMAND is the full command which outputs are being monitors
#
# RESULT
#   returns COMMAND exit-code
#
# EXAMPLES
#   monitor "echo OUT=" "echo ERR=" /bin/bash -c "FOOBAR; echo Done."
#   monitor myfunction1 myfunction2 /bin/bash -c "FOOBAR; echo Done.;/bin/false"
#
monitor () {
    monitor_exit_code "$@" 1001>&1 1002>&2
}

monitor_exit_code () {
    local code=0
    while read data
    do
        code=$data
    done < <( monitor_stdout "$@" 1000>&1 )
    return $code
}


monitor_stdout () {
    local parser_out=$1;shift
    while read data
    do
        ($parser_out "$data") >&1001 
    done < <( monitor_stderr "$@" 1001>&1 )
}

monitor_stderr () {
    local parser_err=$1;shift
    while read data
    do
        ($parser_err "$data") >&1002 
    done < <( "$@" 2>&1 1>&1001 ; echo >&1000 $?  ) 
}
于 2013-09-24T13:02:47.727 回答