Using fork in Ruby on Rails for creating parallel process Using fork in Ruby on Rails for creating parallel process ruby ruby

Using fork in Ruby on Rails for creating parallel process


The problem is that a forked process inherits some of its parent's resources, such as its file descriptors. In particular one such shared resource is the MySQL connection. When the child process finishes its email sending and exits it closes the MySQL connection, which closes the parent processes connection.

If you do continue down this path (and it is frought with similar subtleties) then you need to do something like this:

# Clear existing connections before forking to ensure they do not get inherited.::ActiveRecord::Base.clear_all_connections! fork do  # Establish a new connection for each fork.  ::ActiveRecord::Base.establish_connection     # The rest of the code for each fork...end

You'll have to do similar thing with services like memcached or mongodb if you use those.


Be extremely careful when using fork with rails/passenger, it can become very messy! Instead, you should use resque or delayed_job for this task!


You can reestablish the connection inside of the fork:

dbconfig = YAML::load(File.open('your_app_dir/config/database.yml'))ActiveRecord::Base.establish_connection(dbconfig['development'])