Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

background/daemon process

Tags:

ruby

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
like image 333
veccy Avatar asked Apr 17 '26 23:04

veccy


2 Answers

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

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).

like image 34
Colin Surprenant Avatar answered Apr 20 '26 10:04

Colin Surprenant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!