Search code examples
rubynohup

Is it possible to ignore SIGHUP in Ruby?


I want to create a Ruby script, which will start like this:

$ ruby script.rb &

Then, I will close the console and it must stay alive, working in the background. At the moment I have to run it like this, in order to achive that:

$ nohup ruby script.rb &

I want to get rid of nohup and deal with SIGHUP directly inside the script -- simply ignore it. Is it possible?


Solution

  • Sure, just Signal.trap HUP signal:

    def do_fork
      $pid = fork do
        Signal.trap("HUP") do
          puts "Received HUP, ignoring..."
        end
        Signal.trap("TERM") do
          puts "Received TERM, terminating..."
          exit(0)
        end
        while true do sleep(10_000) end
      end
    
      Process.detach($pid)
    end
    
    do_fork
    

    Copy the code above to some file and run it with ruby file.rb to see it ignores kill -HUP pid and closes on kill -TERM pid.