Reputation: 1210
I am launching a nohup remote script with Ruby Net/SSH.
Net::SSH.start(ip_address, user, options) do |ssh|
script = File.join(remote_path, 'run_case.py')
cmd = "nohup python #{script} #{args} < /dev/null &"
ssh.exec(cmd)
end
All stdout
and stderr
is saved to a file on the remote machine.
Is it possible to get the PID of the remote script so that I can kill it if needed?
EDIT 1: I have modified the script as suggested.
Net::SSH.start(ip_address, user, options) do |ssh|
script = File.join(remote_path, 'run_case.py')
cmd = "nohup python #{script} #{args} < /dev/null & echo $! > save_pid.txt"
ssh.exec(cmd)
pid = ssh.exec!("cat save_pid.txt")
puts mesh_pid
end
It complains that it cannot find the file. Is this because the file does not exist yet? I would prefer to avoid any sleep
command if possible
EDIT 2: Maybe this is not elegant but it works. I have created a second ssh
session and used pgrep
.
Net::SSH.start(ip_address, user, options) do |ssh|
script = File.join(remote_path, 'run_case.py')
cmd = "nohup python #{script} #{args} < /dev/null &"
ssh.exec(cmd)
end
Net::SSH.start(ip_address, user, options) do |ssh|
cmd = "python #{script} #{args}"
mesh_pid = ssh.exec!("pgrep -f '#{cmd}'")
puts mesh_pid
end
Upvotes: 1
Views: 476
Reputation: 3792
You should be able to determine the PID (and store it in a file) as follows:
Net::SSH.start(ip_address, user, options) do |ssh|
script = File.join(remote_path, 'run_case.py')
cmd = "nohup python #{script} #{args} < /dev/null & echo $! > save_pid.txt"
ssh.exec(cmd)
end
In a script, $! represents the PID of the last process executed. If you need to kill the process, you can do it via:
kill -9 `cat save_pid.txt`
rm save_pid.txt
Upvotes: 2