STDOUT输出获取写入到自定义的文件描述符 [英] STDOUT output getting written to custom file descriptor
问题描述
我有一个打开的文件描述符于fd 3,它重定向到一个文件中的函数。我的问题是,从其他功能stdout是越来越写入到FD3被写入文件。因此,code是类似下面。
我不明白,在start_report功能开放文件描述符3如何允许从日志或写入到STDOUT被写入到/tmp/testfile.log任何其他功能输出。奇怪的是,并非所有的标准输出获取写入于fd 3,只有一些。
start_report(){
EXEC 3> /tmp/testfile.log猫<<&EOF GT;及3
一些文本被写入报告。
EOF
}report_update(){
猫<<&EOF GT;及3
一些文字被写入报告。
EOF
}end_report(){
猫<<&EOF GT;及3
一些文本结束写入报告。
EOF
EXEC 3>&安培; -
}日志(){
#$ 1 =函数名
#$ 2 =日志消息
回声$ 1$ 2
}主(){
start_report
登录$ {FUNCNAME [0]}启动主
update_report
登录$ {FUNCNAME [0]}更新报告
end_report
}主要
语句
EXEC 3> /tmp/testfile.log
打开 /tmp/testfile.log
文件描述符3在执行该语句的外壳。即使它出现在函数内部,它会影响执行该功能的外壳;即,它不作用域功能的主体。一旦 start_report
是由当前的shell执行,文件描述符3保持连接到 /tmp/testfile.log
直到关闭或重新分配。
日志
,但是,不写文件描述符3;它只写到标准输出(文件描述符1)。其他功能调整其命令的标准输出文件描述符3。
I have a function that opens a file descriptor to fd 3 which redirects to a file. The issue I have is that STDOUT from other functions is getting written to the file that fd3 is writing to. So the code is something like below.
I don't understand how opening file descriptor 3 at start_report function allows output from log or any other function that writes to STDOUT to be written to /tmp/testfile.log. The odd thing is that not all STDOUT is getting written to fd 3, only some.
start_report () {
exec 3>/tmp/testfile.log
cat <<EOF >&3
Some text is written to a report.
EOF
}
report_update () {
cat <<EOF >&3
some more text is written to a report.
EOF
}
end_report () {
cat <<EOF >&3
some ending text is written to a report.
EOF
exec 3>&-
}
log () {
#$1 = function name
#$2 = log message
echo "$1" "$2"
}
main () {
start_report
log "${FUNCNAME[0]}" "Starting main"
update_report
log "${FUNCNAME[0]}" "updating report"
end_report
}
main
The statement
exec 3> /tmp/testfile.log
opens /tmp/testfile.log
on file descriptor 3 in the shell that executes the statement. Even though it occurs inside a function, it affects the shell that executes the function; i.e., it is not scoped to the body of the function. Once start_report
is executed by the current shell, file descriptor 3 remains attached to /tmp/testfile.log
until it is closed or reassigned.
log
, however, doesn't write to file descriptor 3; it only writes to standard output (file descriptor 1). The other functions redirect the standard output of their commands to file descriptor 3.
这篇关于STDOUT输出获取写入到自定义的文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!