avdi (owner)

Forks

Revisions

  • 0120fc avdi Tue Jun 30 08:44:15 -0700 2009
  • ac43a4 avdi Mon Jun 29 10:13:57 -0700 2009
gist: 137705 Download_button fork
public
Description:
Companion code for http://devver.net/blog/2009/06/a-dozen-or-so-ways-to-start-sub-processes-in-ruby-part-1
Public Clone URL: git://gist.github.com/137705.git
Embed All Files: show embed
ruby_subprocesses_part_1.rb #
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
40
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