You are here

popen 구현 하기

admin의 아바타

커맨드 기반 프로그램의 stdout을 캡쳐하는 코드입니다.

#  From

namespace eval subprocess {

# this will be set to 1 when the subprocess has finished
variable finished 0

# here we can save the output of the subprocess

variable output {}

proc subprocess::handledata {f} {
    variable finished
    variable output
    if {[eof $f]} {
        set finished 1
    } else {
        set x [read $f]
        puts -nonewline $x
        append output $x

proc subprocess::handledata run {cmd} {
    variable finished
    set finished 0
    variable output
    set output {}

    fconfigure stdout -buffering none
    set f [open |$cmd]

    # -buffering none ensures we can read output char by char, instead of line by line
   # line by line reading may require -translation to be set
    fconfigure $f -buffering none -blocking 0

    fileevent $f readable [list [namespace current]::handledata $f]
   # vwait waits for the named variable to change
    vwait [namespace current]::finished
    close $f

set cmd ./

puts "Opening $cmd"
::subprocess::run $cmd
puts "Finished! Output was '$::subprocess::output'"