开发者

In Tcl on Unix, how do I kill a background process that has been launched with exec?

I would like to launch a Unix background process from within a Tcl program by using Tcl's exec command. However, I'd like to progr开发者_运维百科ammatically kill the background process from the same Tcl program at some arbitrary time in the future. How can I best accomplish 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?

%


While in the tclsh environment, you should still have access to commands like ps and kill. I re-created your loop script 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're wanting to do this from a tcl script, here is a short example which shows the results of ps after the exec'ed process has been started and then after it has been 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 kill in different directories, you will have to modify the script accordingly.


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

Run the kill program

exec kill $pid

Use the kill command from Tclx

package require Tclx
kill $pid

Both work. Both let you optionally specify a signal to send instead of the default (SIGTERM). Both let you send the signal to more than one process at once.


The exec command will actually return the PID of a process it starts, which is clear if you RTM or try this on an interactive shell.

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

% set pid [exec echo "hello" &]
25623
% hello
% echo $pid
25623
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜