Louis-Philippe
2/16/2009 9:19:00 PM
[Note: parts of this message were removed to make it a legal post.]
"What is causing the first call to fork to be tied to the first process
and the second call to fork to be tied to the second process? Is it
simply that it's returning the pid of the most recently spawned process?
essentially with:
fork { # code body }
or also
fork do
# code body
end
syntax,
you're just executing a block of code as a child process, completely
separated from its parent from the point it forks, there is no complicated
tie over there,
the fork returns its pid when its initiated, you can then use Process.kill
to kill it but may also want to kill it from the inside with Kernel.exit
2009/2/16 David Masover <ninja@slaphack.com>
> Michael Satterwhite wrote:
>
>> David Masover wrote:
>>
>>
>>
>>> Yes. The parent process should have the process ID of the child. With
>>> that you can do things like:
>>>
>>> if (pid = fork)
>>> sleep 1
>>> Process.kill('TERM', pid)
>>> else
>>> loop do
>>> puts 'KILL ME'
>>> end
>>> end
>>>
>>>
>>
>> on the line
>> if (pid = fork)
>>
>> Is fork returning the pid of the spawned process or of the current (e.g.
>> parent) process?
>>
>
> It's returning the pid of the spawned process in the parent process, and
> nil in the spawned process. So in the code above, the 'if' clause is in the
> parent process, and the 'else' clause is in the spawned process.
>
> More to the point, assume that I spawn multiple processes. How can I
>> address each of them?
>>
>
> With multiple pids. Following my pattern above, you'd do:
>
> if pid1 = fork
> if pid2 = fork
> # parent process
> else
> # inside pid2
> end
> else
> # inside pid1
> end
>
> You could also create arbitrary process trees:
>
> if child = fork
> # parent process
> elsif grandchild = fork
> # child process
> else
> # grandchild process
> end
>
> Now, Louise-Philippe has some more elegant syntax, where you can pass a
> block that will be executed in the spawned process. But the idea is the
> same. Also worth noting, my examples above are the same relatively low-level
> concept used everywhere else on Unix.
>
> So, translating my example above:
>
> child = fork do
> grandchild = fork do
> # grandchild process
> end
> # child process
> end
> # parent process
>
>