Alex Rivera | Logout

How to fire and forget a subprocess?

Asked 2009-04-30T10:12:23.440
22

I have a long running process and I need it to launch another process (that will run for a good while too). I need to only start it, and then completely forget about it.

I managed to do what I needed by scooping some code from the Programming Ruby book, but I'd like to find the best/right way, and understand what is going on. Here's what I got initially:

exec("whatever --take-very-long") if fork.nil?
Process.detach($$)


So, is this the way, or how else should I do it?

After checking the answers below I ended up with this code, which seems to make more sense:

(pid = fork) ? Process.detach(pid) : exec("foo")


I'd appreciate some explanation on how fork works. [got that already]

Was detaching $$ right? I don't know why this works, and I'd really love to have a better grasp of the situation.

Edit
Report

1 Answer

2

Detaching $$ wasn't right. From p. 348 of the Pickaxe (2nd Ed):

$$ Fixnum The process number of the program being executed. [r/o]

This section, "Variables and Constants" in the "Ruby Language" chapter, is very handy for decoding various ruby short $ constants - however the online edition (the first

So what you were actually doing was detaching the program from itself, not from its child. Like others have said, the proper way to detach from the child is to use the child's pid returned from fork().

answered 2009-04-30T12:37:53.730

Your Answer