I need to be able to kill system commands which have run too long. I
tried the following code to no avail:
include Process
#fork a process:
kidpid = fork do
puts "In child, pid = #$$"
system('du /') #or some command that takes a long time
end
puts "after fork: pid of parent is: #$$"
#start a timer in the parent:
killed = 0
counter = 0
afterpid = nil
while (! afterpid = waitpid( kidpid, Process::WNOHANG ) )
puts "inside loop after pid is: #{afterpid}"
sleep 1
counter = counter + 1
puts counter
if ( counter > 2 ) #should kill it after two seconds
kill "SIGTERM", kidpid
killed = 1
end
end
puts "after pid is: #{afterpid}"
I find that if I replace the system call with a command internal to Ruby
(sleep 20) that it works as expected. But spawning a system command seems
to be unkillable. I also find that after the timeout happens and the kill
has been run, that the 'du /' is then not stoppable with ^C.
I do something very similar to this in perl code that
works... the system command is killed and the program continues on its
way.
Phil