问题
I'm trying to create a tcl proc, which is passed a shell command as argument and then opens a temporary file and writes a formatted string to the temporary file, followed by running the shell command in background and storing the output to the temp file as well.
Running the command in background, is so that the proc can be called immediately afterwards with another arg passed to it, writing to another file. So running a hundred such commands should not take as long as running them serially would do. The multiple temp files can finally be concatenated into a single file.
This is the pseudocode of what I'm trying to do.
proc runthis { args }
{
set date_str [ exec date {+%Y%m%d-%H%M%S} ]
set tempFile ${date_str}.txt
set output [ open $tempFile a+ ]
set command [concat exec $args]
puts $output "### Running $args ... ###"
<< Run the command in background and store output to tempFile >>
}
But how do I ensure the background'ing of the task is done properly? What would need to be done to ensure that the multiple temp files get closed properly?
Any help would be welcome. I'm new at tcl and finding to get my mind around this. I read about using threads in tcl but I'm working with an older version of tcl which doesn't support threading.
回答1:
How about:
proc runthis { args } {
set date_str [clock format [clock seconds] -format {+%Y%m%d-%H%M%S}]
set tempFile ${date_str}.txt
set output [ open $tempFile a+ ]
puts $output "### Running $args ... ###"
close $output
exec {*}$args >> $tempFile &
}
See http://tcl.tk/man/tcl8.5/TclCmd/exec.htm
Since you seem to have an older Tcl, replace
exec {*}$args >> $tempFile &
with
eval exec [linsert $args 0 exec] >> $tempFile &
来源:https://stackoverflow.com/questions/13903727/running-shell-commands-in-background-in-a-tcl-proc