如何在没有管道/ fifos的情况下将stderr和stdout重定向到2个不同的函数?

时间:2013-09-24 13:02:48

标签: bash function redirect exit-code

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

1 个答案:

答案 0 :(得分: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 $?  ) 
}