Ruby/Threads/fork
Материал из Wiki.crossplatform.ru
Содержание |
Environment in Child thread
ENV["alpha"] = "123" ENV["beta"] = "456" fork do x = ENV["alpha"] ENV["beta"] = "789" y = ENV["beta"] puts " Child: alpha = #{x}" puts " Child: beta = #{y}" end Process.wait a = ENV["alpha"] b = ENV["beta"] puts "Parent: alpha = #{a}" puts "Parent: beta = #{b}"
Fork a child process
fork { puts "Hello from the child process: #$$" } puts "Hello from the parent process: #$$"
fork a number of listening processes to increase the maximum number of connections
require "socket" server = TCPServer.new(1234) 5.times do fork do while connection = server.accept while line = connection.gets break if line =~ /quit/ puts line connection.puts "Received!" end connection.puts "Closing the connection. Bye!" connection.close end end end
fork is a method provided by the Kernel module that creates a fork of the current process.
# fork returns the child process"s process ID in the parent, but nil in the child process # You can use this to determine which process a script is in. # forks the current process into two processes, and only executes the exec command within the child process (the process generated by the fork): if fork.nil? exec "ruby some_other_file.rb" end puts "This Ruby script now runs alongside some_other_file.rb"
fork with block
fork do puts "In child, pid = #$$" exit 99 end pid = Process.wait puts "Child terminated, pid = #{pid}, status = #{$?.exitstatus}"
Is it a parent process or a child process
pid = fork if (pid) puts "Hello from parent process: #$$" puts "Created child process #{pid}" else puts "Hello from child process: #$$" end