In Tcl on Unix, how do I kill a background process that was started using exec?

I would like to start a Unix background process from a Tcl program using the Tcl exec command. However, I would like to programmatically kill the background process from the same Tcl program at some arbitrary point in the future. How can i do this?

bash$ cat loop.bash #!/bin/bash while [ 1 ]; do sleep 5; done; bash$ tclsh % exec /home/dana/travis/loop.bash & 6598 % puts "How do I kill the background process started by the previous exec command?" How do I kill the background process started by the previous exec command? % 
+4
source share
3 answers

In tclsh, you should still have access to commands like ps and kill . I recreated your script loop and then went into a tclsh session:

 $ tclsh % exec /path/to/loop.sh & 22267% ps PID TTY TIME CMD 19877 pts/0 00:00:00 bash 22212 pts/0 00:00:00 emacs-x 22317 pts/0 00:00:00 tclsh 22319 pts/0 00:00:00 loop.sh 22326 pts/0 00:00:00 sleep 22327 pts/0 00:00:00 ps % kill 22319 % ps PID TTY TIME CMD 19877 pts/0 00:00:00 bash 22212 pts/0 00:00:00 emacs-x 22317 pts/0 00:00:00 tclsh 22332 pts/0 00:00:00 ps 

If you want to do this from a tcl script, here is a short example that shows the results of ps after the exec'ed process has been started, and then after it has stopped:

 #!/usr/bin/tclsh set id [exec /path/to/loop.sh &] puts "Started process: $id" set ps [exec /bin/ps] puts "$ps" exec /usr/bin/kill $id puts "Stopped process: $id" set ps [exec /bin/ps] puts "$ps" 

If your system has ps and kills in different directories, you will have to modify the script accordingly.

+3
source

The exec command will actually return the PID of the process that will be launched, which is clear if you are using RTM or try this in an interactive shell.

This can be used in conjunction with the kill command, as suggested by GreenMatt.

 % set pid [exec echo "hello" &] 25623 % hello % echo $pid 25623 
+1
source

There are two ways to kill the background process, assuming that you saved the PID (in a variable called pid for the argument):

Run the kill program

 exec kill $pid 

Use kill command from Tclx

 package require Tclx kill $pid 

Both work. Both options allow you to specify the signal to send instead of the default value (SIGTERM). Both allow you to immediately send a signal to several processes.

+1
source

Source: https://habr.com/ru/post/1340046/


All Articles