public
Last active

  • Download Gist
ruby_subprocesses_part_1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
require 'rbconfig'
 
$stdout.sync = true
 
def hello(source, expect_input)
puts "[child] Hello from #{source}"
if expect_input
puts "[child] Standard input contains: \"#{$stdin.readline.chomp}\""
else
puts "[child] No stdin, or stdin is same as parent's"
end
$stderr.puts "[child] Hello, standard error"
end
 
THIS_FILE = File.expand_path(__FILE__)
 
RUBY = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name'])
 
if $PROGRAM_NAME == __FILE__
puts "1. Backtick operator"
output = `#{RUBY} -r#{THIS_FILE} -e'hello("backticks", false)'`
output.split("\n").each do |line|
puts "[parent] output: #{line}"
end
puts
 
puts "2. Kernel#system"
success = system(RUBY, "-r", THIS_FILE, "-e", 'hello("system()", false)')
puts "[parent] success: #{success}"
puts
 
puts "3. Kernel#fork"
pid = fork do
hello("fork()", false)
end
Process.wait(pid)
puts "[parent] pid: #{pid}"
puts
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.