[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Getting process id of started process
From:       Brian Candler <B.Candler () pobox ! com>
Date:       2005-03-31 17:26:52
Message-ID: 20050331172613.GB1658 () uk ! tiscali ! com
[Download RAW message or body]

On Thu, Mar 31, 2005 at 09:02:02AM +0900, Joe Van Dyk wrote:
> On Wed, 30 Mar 2005 14:57:51 -0800, Joe Van Dyk <joevandyk@gmail.com> wrote:
> > Say I want to start a long running shell process (and monitor that process).
> > 
> >     def start_process
> >         @process_id = fork do
> >             Kernel.system "cat /dev/zero > /dev/null"
> >         end
> >     end
> > 
> > However, @process_id doesn't contain the pid of the cat process.  How
> > can I capture the pid of that process?

It won't, because Kernel.system also does a fork, runs the 'cat' as a child,
waits for it to finish, and then continues.

You will get the pid of the cat process if you change Kernel.system "cat..."
to
        exec "cat ..."

But then, the child Ruby process *becomes* cat at that point, and so when
cat terminates, the child terminates.

If you want to capture the pid of the 'cat' then you can reimplement
Kernel.system yourself - which is basically just fork and exec anyway.

It depends what you want to do with the variable @process_id later. If you
just want the child to run cat and then terminate, then 'exec' is what you
want.

In fact, I can't see what else you would want. Suppose I wrote:

    def start_process
        @process_id = fork do
            Kernel.system "cat /dev/zero > /dev/null"
            Kernel.system "cat /dev/null > /dev/null"
            Kernel.system "cat /dev/zero > /dev/null"
        end
    end

which process ID would you want returned in @process_id ? You currently get
the (child) Ruby process, which then runs three grandchildren one after
another. I can't see how else it would usefully work, unless you get the pid
of each of the three grandchildren and communicate it back to the parent
somehow (e.g. over a socket). The pid for each grandchild won't be known
until that particular grandchild is started, of course.

Regards,

Brian.

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic