I need to run console command in ruby (in my case to start Gvim), get PID of Gvim and kill that process in a few seconds.
If I do the following - it gives me PID of parent process, but I need somehow to find out the PID of Gvim.
IO.popen("gvim file_name_to_open" { |gvim|
puts gvim.pid
}
If I do the following, it just starts Gvim and does nothing more (I need Gvim process to be killed).
pid = Process.spawn("gvim", "file_name_to_open")
sleep(5)
Process.kill(9, pid)
Process.wait pid
What am I doing wrong?
The most appropriate solution looks like this:
parent_pid = Process.spawn("gvim", "file_name_to_open")
# Need to wait in order not to kill process till Gvim is started and visible
sleep(5)
Process.kill(9, parent_pid)
# Try to get all Gvim PIDs: the result will look like list of PIDs in
# descending order, so the first one is the last Gvim opened.
all_gvim_pids = `pidof gvim`
last_gvim_pid = all_gvim_pids.split(' ').map(&:to_i).first
Process.kill(9, last_gvim_pid)
The solution is strange and hacky, but noone has better ideas :(