2

In a ruby process I fork off a child with a system call in it.

I want to be able to kill the child and have that propagate to the system call, but the system call keeps running:

unless pid=fork
  system("echo start ; sleep 1 ; echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3")
  exit
end
puts "Child: #{pid}"

sleep 2

Process.kill('-KILL',-pid)

How can I propagate the kill from ruby to it's forked system call?

1 Answers1

1

Apparently, system blocks. Use exec instead: http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-exec

  unless pid=fork
    puts pid
    exec("echo start ; sleep 1 ; echo 1 ; sleep 1 ; echo 2 ; sleep 1 ; echo 3")
    exit
  end
  puts "Child: #{pid}"

  sleep 1

  Process.kill('KILL',pid)
  puts 'killed'
Satya
  • 4,458
  • 21
  • 29
  • Actually, this doesn't quite answer the question. If I have a ruby script that has a 'system' call with, for example, a sleep in it, then I can kill it with ctrl-c (UNIX). But I can't kill the system call by sending the KILL signal to the ruby script. Is that because the ctrl-c goes to the child/system() and it is sent up from the child? – David Ljung Madison Stellar Nov 29 '15 at 02:33
  • Hmm, I don't know why Process.kill isn't terminating the child process, sorry. I checked, now, that ctrl-C does indeed terminate both processes while using `system`. You can un-accept my answer if you like. – Satya Nov 30 '15 at 15:05
  • Actually, I'll just leave it accepted since it's helped me figure out what the real question is - why ctrl-c acts different than Process.kill I'm guessing that the ctrl-c is sent to the child instead of being propagated by the parent. – David Ljung Madison Stellar Dec 01 '15 at 16:42