Kill a system process in Ruby Thread

How can I kill ping (or another VERY LONGEST without a timeout, etc. system process) (ping is just a simple example) in ruby ​​Thread:

a = Thread.new do
    system 'ping localhost'
end

a.kill
a.exit
a.terminate

while true
    sleep 5
    p a.alive?
end

Output: =>

PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=1 ttl=64 time=0.023 ms
....
true
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=7 ttl=64 time=0.022 ms
.....
true
......

So, I need to stop the ping process with Thread, but I do not know how to do this.

+4
source share
1 answer

systemdoes not give you pid.

Use Process::spawn. And use Process::killto kill the process using the pid returned Process::spawn.

For example:

pid = Process.spawn('ping localhost')
sleep 3
Process.kill(:TERM, pid)
Process.wait(pid)
+5
source

All Articles