Posted to tcl by nscerqueira at Mon Sep 06 14:21:50 GMT 2010view raw

  1. set cmd1 " ls -la"
  2. set cmd2 " ls -lh"
  3.  
  4. proc isReadable { f } {
  5. # The channel is readable; try to read it.
  6. set status [catch { gets $f line } result]
  7. if { $status != 0 } {
  8. # Error on the channel
  9. puts "error reading $f: $result"
  10. set ::DONE 2
  11. } elseif { $result >= 0 } {
  12. # Successfully read the channel
  13. puts "got: $line"
  14. } elseif { [eof $f] } {
  15. # End of file on the channel
  16. puts "end of file"
  17. set ::DONE 1
  18. } elseif { [fblocked $f] } {
  19. # Read blocked. Just return
  20. } else {
  21. # Something else
  22. puts "can't happen"
  23. set ::DONE 3
  24. }
  25. }
  26.  
  27.  
  28.  
  29. # Open a pipe
  30. set fid1 [open "|$cmd1"]
  31. set fid2 [open "|$cmd2"]
  32.  
  33. # Set up to deliver file events on the pipe
  34. # fconfigure $fid -blocking false
  35. fileevent $fid1 readable [list isReadable $fid1]
  36. fileevent $fid2 readable [list isReadable $fid2]
  37.  
  38. # Launch the event loop and wait for the file events to finish
  39. vwait ::DONE
  40.  
  41. # Close the pipe
  42. close $fid1
  43. close $fid2

Comments

Posted by dkf at Mon Sep 06 14:27:17 GMT 2010 [text] [code]

As long as you close the channel on [eof], you don't need to manually test for errors from [gets]. It only errors out (when non-blocking) if the channel is closed.