3

I have a script that is coded in the manner below. I want to run this as a background/daemon process however once I start the script, if then I close the terminal window that it was run from the program terminates. What do I need to do to keep the program running

loop do

  pid = fork do
    ..........
    ..........
    ..........
  end

  Process.detach(pid)
end
veccy
  • 925
  • 3
  • 12
  • 20

3 Answers3

9

All the answers above fail to actually show how easy it is to do this:

# Daemonize the process and stay in the current directory
Process.daemon(true)

loop do
  pid = Process.fork do
    # Do something funky
  end

  Process.waitpid(pid)

  # Reduce CPU usage
  sleep(0.1)
end
2

This has been answered in details in this stackoverflow question: Create a daemon with double-fork in Ruby

Otherwise, there are a few gems out there to help abstract this out of your code, and in particular you can take a look at Raad (Ruby as a Daemon) https://github.com/colinsurprenant/raad which will also work with JRuby code (I am the author of Raad).

Community
  • 1
  • 1
1

man nohup
nohup - run a command immune to hangups, with output to a non-tty

$ nohup command > output &

amized
  • 337
  • 2
  • 5