1

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
5
  • Why the down vote? Commented Jun 28, 2017 at 9:08
  • I've down-voted because your edit makes no sense. Did you looked even a second at the code before posting it back here? Commented Jun 28, 2017 at 10:07
  • I see. Yes, I had forgotten the change the first command. Damn copy & paste. Commented Jun 28, 2017 at 12:07
  • Does it still complain that the file can't be found? Commented Jun 28, 2017 at 12:20
  • Yes. I had used the correct command in my program, but I pasted the old one here. I logged in the VM and the file is actually there. exec is non blocking so I thought that the second command (cat) is probably executed before the file is actually created. I could use a sleep, but it does not seem a robust approach. Commented Jun 28, 2017 at 12:26

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ok, it will give you the pid now, but it will hang unless you close the connection manually. Try nohup sleep 1000 & in your terminal to see

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.