我需要解压缩命名管道中的文件返回它:
proc unzip_file_if_needed { fileName } {
if { [file extension $fileName] != ".gz" } {
return $fileName;
}
set tmpDir [fileutil::tempdir]
set tmpFileName [ file join $tmpDir [ pid ] ]
if { [file exists $tmpFileName ] } {
file delete $tmpFileName
}
exec mkfifo $tmpFileName
exec gunzip -c $fileName > $tmpFileName &
return $tmpFileName
}
它挂在 exec gunzip -c $fileName > $tmpFileName &
问题是内核将在open()
系统调用中阻塞,直到 fifo 打开相反的方向,并且 Tcl 在分叉之前在父进程中创建重定向(因为这允许在正常情况下进行更可靠的错误处理)。您需要的是将 O_NONBLOCK
标志传递到open()
系统调用中,但 exec
命令无法控制它。所以需要一些诡计!
set fd [open $tmpFileName {WRONLY NONBLOCK}]
exec gunzip -c $fileName >@$fd &
close $fd
这是通过使用我们想要的标志手动执行open
(Tcl 将它们映射而不带O_
前缀),然后将该描述符传递给子进程。请注意,由于这是我们正在设置的管道的写入侧,因此我们必须以WRONLY
模式打开(这是open … w
在幕后会做的事情,减去一些在这里不适用的标志,再加上我们想要的魔术NONBLOCK
)。
我用这种方式解决了这个问题:
proc unzip_file_if_needed { fileName } {
if { [file extension $fileName] != ".gz" } {
return $fileName;
}
set tmpDir [fileutil::tempdir]
set pId [pid]
set tmpFileName [ file join $tmpDir pId ]
set unzipCmd [ file join $tmpDir [ append pId "cmd.sh" ] ]
if { [file exists $tmpFileName ] } {
file delete $tmpFileName
}
if { [file exists $unzipCmd ] } {
file delete $unzipCmd
}
set cmdDesc [open $unzipCmd { CREAT EXCL RDWR} 0777]
puts $cmdDesc "#!/bin/bashn gunzip -c $1 > $2"
close $cmdDesc
exec mkfifo $tmpFileName
exec $unzipCmd $fileName $tmpFileName >&@1 &
return $tmpFileName
}