我可以在Tcl中找到文件句柄中的文件名吗?

时间:2012-02-28 17:02:56

标签: file tcl filenames channel filehandle

Can I find a filename from a filehandle in Perl?类似,但在Tcl。

我计划缓存filename-filehandle关联,所以我纯粹是出于好奇 - 特别是链接中提到的“操作系统魔法”。在Tcl中有可能吗?

如果重要的话,我(强迫)在SunOS 5.10上使用Tcl 8.0.5。

3 个答案:

答案 0 :(得分:5)

对于旧的Tcl版本,你真的没有那么多的选择。最简单的方法是对openclose进行一些包装:

rename open _original_open
rename close _original_close

proc open {filename args} {
    global fileForChannel
    set channel [eval [list _original_open $filename] $args]
    set fileForChannel($channel) $filename
    return $channel
}
proc close {channel} {
    global fileForChannel
    catch {unset fileForChannel($channel)}
    _original_close $channel
}

然后,您只需阅读$ch即可获取开放频道$fileForChannel($ch)的文件名。

答案 1 :(得分:1)

我看了,没有找到任何方法从句柄获取文件名,所以我创建了自己的解决方案。此解决方案使用跟踪命令捕获打开命令退出的时间。此时,文件名和句柄都可用,因此我通过全局 fileNameFromHandle 数组将它们相互关联。

# This script demonstrate the use of the trace command to keep track
# the relationship between file handles and file names

# ======================================================================
# Setup trace to track file handle vs. file name
array set fileNameFromHandle {}
proc trace_proc {command code result op} {
    if {$code != 0} return; # Ignore failed calls

    set filename [lindex $command 1]; # command = {open filename mode}
    set filehandle $result
    set ::fileNameFromHandle($filehandle) $filename
}
proc getFileName {handle} { return $::fileNameFromHandle($handle) }
trace add execution open leave trace_proc

# ======================================================================
# Main
set handle1 [open file1.txt r]

# Do something with the files

# Need filename from handle?
puts "Handle: $handle1, filename: [getFileName $handle1]"

close $handle1

更新

我没有Tcl 8.0.5来验证此解决方案是否有效。请试一试,让我知道。您还可以跟踪关闭命令以删除关联。

答案 2 :(得分:0)

你可以运行: exec lsof | grep -w [pid] | grep -w [fstat $ file_handle ino]

相关问题