Forking a .rb file process into the background

#1

I have a script that takes a few seconds to complete. I would like to fork it into the
background, so that it continues to do its job, while allowing me to work with bash.

There are some workarounds such as forking in shell I guess, but I want to really
start the script, spawn a daemon, let it work there without me having to wait
on the commandline.

Now - there are some hints on the www but nothing that is really simple.

I guess what I need is some mini-daemon that does the job, while it allows
for me to continue to work with bash. Does anyone have some suggestions
or perhaps even has a script that does something like this?

Specifcally I would need the .rb file to output something, such as “forking
to background”, and then immediately allow me to continue to work with
bash after that message. I know how to use Thread.new() but this still
requires an actively running .rb file; I need something more like fork/spawn
or Process daemon but ideally something that is SUPER simple. Ideally
something I could copy paste in a minimal way, even better if I would
NOT have to depend on any external gem that does it for me - I really
want this to be purely standalone in that .rb file as much as possible.

#2

see
http://www.tweetegy.com/2012/04/forking-ruby-processes-or-how-to-fork-ruby/

#3

It is really simple.

p1 = fork { sleep 3; puts "detached proc id: #{Process.pid}" }
Process.detach(p1)
puts "main finished"

See Process::detach for details.

3 Likes
#4

I’m wondering: Why do you need to fork the process into the background?
Could you start it up as a background process? E.g.:
ruby scratch.rb &

#5

You can use the open3 gem from the standard library:
Here script.rb is the another file name:

require 'open3'
    p :Started! if Open3.pipeline_start(
            "#{File.join(RbConfig::CONFIG['bindir'], 'ruby')} #{File.join(File.dirname(__FILE__), 'script.rb')}"
    )
#6

Easiest way. Make a .bash_aliases file in your /home/usr dir.

In it add
ruby path/to/script/my_script.rb &
Making a .bash_aliases will start any script you add into it at the user login level.

The & is the important part. It what tells the kernel to run it in the background.

If you need a script to run at BOOT, add the same thing but in the.rc_local file.

#7

I don’t think that’s the answer. Say you want to make a professional software (or a huge game). You need to open a window in separate thread. Would you suggest your users / players to alias it? That’s a bad practice. I would suggest the OP to use either Open3, or just use class Thread.