user2141046
user2141046

Reputation: 902

How to make tcl background proc wait on a file?

I'm trying to write a proc that waits in the background on a file and launches a command and keeps on getting stuck while waiting
My code:

proc stuck_on_kuku {} {  
      while {![file exists kuku]} {   
          after 3000    
      }  
   echo done sleeping ; # here my command should appear
}  

Now, when I call this proc in background mode, it jams my shell until done. The shell is recording key strokes, but will only consider them after the kuku file is created
> after idle stuck_on_kuku
Also tried to create an uplevel version of the proc, but still gets the same behavior.
Isn't there a way to wait for a file creation without jamming the tcl shell?
My goal is to have 2-3 of these background runs in parallel, each waiting on something else and launching something else.

Oh, and - worth a mention - I have no access to the Threads package on this env, so must make do with vanilla tcl 8.6

Upvotes: 1

Views: 1356

Answers (1)

slebetman
slebetman

Reputation: 113866

The after command has a blocking and non-blocking mode. You're using it in a blocking way. Simply use it's non-blocking mode:

proc stuck_on_kuku {} {
    if {[file exists kuku]} {
        echo done sleeping ; # here your command should appear
    } else {
        after 3000 stuck_on_kuku; # simulated "threading" without threads
    }
}

Note that with this set-up you can check the condition much more often and not consume much CPU time. Try after 100 to check 10 times per second and use almost 0% CPU time.

Upvotes: 3

Related Questions