Skip to content

Instantly share code, notes, and snippets.

@timrandg
Created May 25, 2012 06:55
Show Gist options
  • Select an option

  • Save timrandg/2786269 to your computer and use it in GitHub Desktop.

Select an option

Save timrandg/2786269 to your computer and use it in GitHub Desktop.
fork explanation code
parent = Process.pid
puts parent.to_s + ": the parent process id"
forked_id = fork{ exec('ls | grep back')}
#^from that carrot in the line above, a child process is forked from the current (which is then parent) process.
#because there are two processes running, forked_id will be assigned in each process--e.g. two forked_id varaibles are created.
#in the child it is nil, but in the parent it is the child's pid. If a block is provided to fork, the child executes the block contents and
#ends. It may seem that the child process returns after the parent, but if the parent's task is long, the child may return in the middle
#of the parents job.
puts "fork returns #{forked_id.nil? ? 'nil' : forked_id} to " + Process.pid.to_s
puts "which is the #{Process.pid == parent ? 'parent' : 'child'} process"
puts "end of program".center(30, "*")
# =>
# >> 67645: the parent process id
# >> fork returns 67646 to 67645
# >> which is the parent process
# >> ********end of program********
# >> 082711_TR_backup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment