Blogged by Ujihisa. Standard methods of programming and thoughts including Clojure, Vim, LLVM, Haskell, Ruby and Mathematics written by a Japanese programmer. github/ujihisa

Friday, March 5, 2010

All About Spawn

Spawn = Fork + Exec, but works also on platforms which don't support fork.

The usage of spawn is often said to be cryptic. Here I'll describe common cases.

  • system('ls')

    pid = spawn(['ls', 'ls'])
    Process.wait(pid)
    
  • system('ls .')

    pid = spawn('ls', '.')
    Process.wait(pid)
    
  • system('ls . &')

    pid = spawn('ls', '.')
    
  • system('ls . > a.txt')

    pid = spawn('ls', '.', :out => 'a.txt')
    Process.wait(pid)
    
  • system('ls . >> a.txt')

    pid = spawn('ls', '.', :out => ['a.txt', 'a'])
    Process.wait(pid)
    
  • system('ls . >& a.txt')

    pid = spawn('ls', '.', [:out, :err] => ['a.txt', 'w'])
    Process.wait(pid)
    
  • IO.popen('cat a.txt') {|io| p io.read

    i, o = IO.pipe
    spawn('cat a.txt', :out => o)
    o.close
    p i.read
    
  • system('make all &')

    spawn('make', 'all)
    
  • Dir.chdir('a') { system 'make all &' }

    spawn('make', 'all', :chdir => 'a')
    
  • Passing ENV:

    • Shell: $ AAA=1 make all &
    • Ruby: ENV['AAA'] = '1'; system('make all &')
    • Ruby with Spawn: spawn({'AAA' => '1'}, 'make', 'all')

Further information can be available in process.c in ruby trunk. Here the documentation from the file:

No comments:

Post a Comment

Followers