amateur
amateur

Reputation: 951

How to kill the background process in TCL in the windows environment

I have started iperf as the background process from within a Tcl program by using Tcl's exec command in the windows environment. However, I'd like to programmatically kill the iperf process from the same Tcl program at some arbitrary time in the future. How can I best accomplish this?

Here's the code I'm using

proc runtest {  REF_WLAN_IPAddr run_time} {
    exec c:\\iperf_new\\iperf -c $REF_WLAN_IPAddr -f m -w 2M -i 1 -t $run_time  >& xx.txt & 
    # have some code after this
} 

but i see iperf is not killed, and so the control is not transferred back to TCL, how can i do this? The answers are highly appreciated }

Upvotes: 2

Views: 5138

Answers (3)

r00t-err0r
r00t-err0r

Reputation: 184

Or maybe

exec {*}[auto_execok start] C:\\Windows\\System32\\taskkill.exe $pid

or

exec {*}[auto_execok start] C:\\Windows\\System32\\taskkill.exe /F /IM ProgramName.EXE /T

Upvotes: 1

schlenk
schlenk

Reputation: 7247

exec returns the list of subprocess PIDs if used in the way you describe, but Tcl does not have a builtin kill command; those are only available in extensions.

So you have two major options:

  1. Get the TWAPI package http://twapi.magicsplat.com/ and use the end_process function from that package (see http://twapi.magicsplat.com/process.html#end_process)

  2. Use a second exec and run the windows command taskkill with the /PID Option

    exec [auto_execok taskkill] /PID $pid
    

Upvotes: 6

Hai Vu
Hai Vu

Reputation: 40688

Here is a skeleton script I use:

package require Tclx

puts "main begins"

puts "Launch child script"
set childPid [exec tclsh child.tcl 0 &]
puts "Child PID: $childPid"

puts "Do something now..."
after 1000

puts "Now wait for child to finish"
lassign [wait $childPid] pid howEnded exitCode

puts "Process $pid ended with reason ($howEnded) and exit code ($exitCode)"
puts "main ends"

Discussion

  • The script (main.tcl) spawn a child script (child.tcl, or ifperf in your case) and record its process ID to childPid
  • The main script then does something (in this case, after 1000, which simply sleeps for 1000 miliseconds)
  • The main script calls the wait command to wait for the child process to finish. Wait returns a list of 3 things: the process ID, how it ended, and exit code
  • Caveat: if the child finishes before for you call wait, the wait command will throw an exception, you need to catch it.

Here is a sample run:

$ tclsh main.tcl 
main begins
Launch child script
Child PID: 25837
Do something now...
  child runs for 16889 miliseconds
Now wait for child to finish
  child ends
Process 25837 ended with reason (EXIT) and exit code (0) 
main ends

Upvotes: 0

Related Questions