[Rails] Can I fork() in a model?
Ara.T.Howard
Ara.T.Howard at noaa.gov
Sun Mar 13 02:06:14 GMT 2005
On Sat, 12 Mar 2005, LN wrote:
> Hi Everyone,
>
> I have a long running background process that I would like to do with the
> DB but I want the UI to return immediately.
>
> Can I fork within model class method? I am running under FastCGI.
>
> How should the child process terminate itself at the end of the function?
> is Kernel.exit! appropriate? or is plain old Kernel.exit better? Should I
> return a status?
>
> My code thus far:
>
> def self.sortBG(spec)
>
> pid=fork
>
> # in the parent, return now
> if (pid)
> Process.detach(pid)
> return
> end
this simply starts a thread that periodically waits for your child if that
what you want...
>
> # in the child, go ahead with the sort.
>
> # ... DO SOME LENGTHY PROCESSING ...
>
> Kernel.exit!
> end
>
> I am experimenting now but hoped someone out there may have
> tried this already.
>
> Thanks so much,
the biggest issue with the above is that your system will accumulate zombies
if (when - remeber the process manager) your fastcgi process exits. i *think*
what you want to do is become a child of init: being careful not not to
generate any out/err/put... something like:
jib:~/eg/ruby > cat dp.rb
require 'fileutils'
class DetachedProcess
def initialize(*a, &b)
@b = b
end
def run
pid = fork do
[ STDIN, STDOUT, STDERR ].each{|io| io.reopen '/dev/null', 'r+'}
fork{ @b.call(*@a) }
exit!
end
Process::waitpid pid
end
end
dp =
DetachedProcess::new do
sleep 5
FileUtils::touch 'when_grandchild_died'
end
dp.run
puts "#{ Process::pid } exited @ #{ Time::now }"
jib:~/eg/ruby > ruby dp.rb && sleep 5 && stat when_grandchild_died
10021 exited @ Sat Mar 12 19:02:28 MST 2005
File: `when_grandchild_died'
Size: 0 Blocks: 0 IO Block: 8192 Regular File
Device: bh/11d Inode: 16449677 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 447/ ahoward) Gid: ( 447/ ahoward)
Access: 2005-03-12 19:02:33.000000000 -0700
Modify: 2005-03-12 19:02:33.000000000 -0700
Change: 2005-03-12 19:02:33.000000000 -0700
this won't leave behind any zombies AND you don't have to collect the exit
status directly in your app.
HTH.
kind regards.
-a
--
===============================================================================
| EMAIL :: Ara [dot] T [dot] Howard [at] noaa [dot] gov
| PHONE :: 303.497.6469
| When you do something, you should burn yourself completely, like a good
| bonfire, leaving no trace of yourself. --Shunryu Suzuki
===============================================================================
More information about the Rails
mailing list