Forking a .rb file process into the background


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




It is really simple.

p1 = fork { sleep 3; puts "detached proc id: #{}" }
puts "main finished"

See Process::detach for details.


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 &


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')}"

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.


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.