后台运行ruby脚本

Ruby is a powerful dynamical programming language. You can easily use it to build large and complex software.

However, there are times when you just want to use it to make a basic script to automate your workflow, and simply run it by typing: ruby your_script.rb.

The problem comes when you want to let your script run forever, because if you close your console or terminal, the program will get closed too. To solve this problem, you need to make your script run in the background, to make it as a daemon. How?

Actually as of Ruby 1.9, this becomes a fairly simple process, you don’t need any extra library or gem, you can add some code similar like below:

 

 

require 'rubygems'

Process.daemon(true,true)

pid_file = File.dirname(__FILE__) + "#{__FILE__}.pid"
puts pid_file
100.times do 
   sleep 3
   File.open(pid_file, 'a') {|f| f.write Process.pid }
end

 

   

The first line of the code changes your script into a daemon process.

The class method daemon() has two arguments, the first argument controls current working directory. If you don’t set it to true, it will change the current working directory to the root (“/”). The second argument determines the outputs, unless the argument is true, daemon() will just ignore any standard input, standard output and standard error.

The second part of the code creates a file with the same name as your script, and writes the process id into it. The benefit of this code is, later on, you can use some process monitor tools like god, or monit to keep tracking of the status of your script.

After adding the snippet of code, and run your script again. This time your script would just disappear from console. If you use command like:

ps -p your_pid

You can see your script is running happily underground.

 

http://stevenyue.com/2014/10/16/how-to-daemonize-a-ruby-script/#comments

你可能感兴趣的:(Daemon,后台)