Anand
Anand

Reputation: 10400

Child process returns nil for fork call

puts "Process #{Process.pid} started"
return_value = fork
puts "Process #{Process.pid} returned #{return_value}"
puts "Process #{Process.pid} exited"

Above ruby code printed this output to STDOUT

Process 6644 started
Process 6644 returned 6645
Process 6644 exited
Process 6645 returned 
Process 6645 exited

When parent process executes fork, it returns the pid of child process. When the child process calls fork why is it returning nil, shouldn't this be a recursive-kind-of-call? Like.. child also forks another child process.. and that child process forks another process..etc., Am I missing something here?

Upvotes: 0

Views: 403

Answers (2)

Viren
Viren

Reputation: 5962

I guess you do missing a point I you refer the Ruby fork documentation calling a fork with block executed the code below it twice one for the parent and other for the child (fork process) with child fork return nil

You If you inspect your output

Process 6644 started  -- Parent Process Started
Process 6644 returned 6645 -- Parent Process displaying the retrun value = child process id
Process 6644 exited   -- Parent Process exiting
Process 6645 returned  -- Child Process forked earlier and since there return value is nil
Process 6645 exited  -- Child Process exiting

Check Ruby documentation on fork this form of fork declaration is sightly confusing from the block thing which @psyho has answered .

I advice you to use the follow the same declaration that @psycho answered since it is that confusing

Hope this help

Upvotes: 0

psyho
psyho

Reputation: 7212

This is how you distinguish in the code whether the code is running in the parent process or in the child process: the parent process receives the PID of the forked child, and the child gets nil.

Personally, I prefer to use the syntax:

pid = fork do
  # this is the code that will be executed by the child
end

# this is the code executed by parent

Since most of the time, child is supposed to do something other than the parent process, this code reflects the intent much better.

Upvotes: 1

Related Questions