chaining processes, Process.waitpid

Discussion in 'Ruby' started by Thomas Hafner, Apr 14, 2007.

  1. Hello,

    for chaining processes in a way, that the output of one process feeds
    the input of another one like in that example ...

    #\\
    # transformation 'foo' -> 'fee' -> 'tee':
    chain_processes(lambda { exec('echo', 'foo') },
    lambda { exec('sed', 's|o|e|g') }) do
    system('sed', 's|f|t|g')
    end
    #//

    .... I came to that solution:

    #\\
    def chain_processes(*processes, &block)
    saved_stdin = $stdin.clone
    threads = []
    this, *remaining = processes + (block ? [ block ] : [])
    while [] != remaining
    rd, wr = IO.pipe
    child = fork
    if !child
    rd.close
    $stdout.reopen(wr)
    exit this[]
    end
    wr.close
    $stdin.reopen(rd)
    threads << Thread.new { Process.waitpid(child) }
    this, *remaining = remaining
    end

    this[]
    threads.each { |t| t.join }
    $stdin.reopen(saved_stdin)
    end
    #//

    That seems also to work without Process.waitpid(child). When is it
    really necessary to wait for the children? How should an example look
    like which breaks without using Process.waitpid or Process.wait?

    Regards
    Thomas
     
    Thomas Hafner, Apr 14, 2007
    #1
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jeff Rodriguez
    Replies:
    23
    Views:
    1,523
    David Schwartz
    Dec 9, 2003
  2. spawnl and waitpid

    , Feb 27, 2007, in forum: Python
    Replies:
    13
    Views:
    958
  3. lasek

    Fork + Waitpid

    lasek, May 13, 2005, in forum: C Programming
    Replies:
    4
    Views:
    6,241
    SM Ryan
    May 14, 2005
  4. Mike

    'waitpid' query

    Mike, Jan 28, 2009, in forum: C Programming
    Replies:
    10
    Views:
    718
    Kenny McCormack
    Jan 29, 2009
  5. Fan
    Replies:
    1
    Views:
    437
    Christopher Head
    Jul 16, 2011
  6. Thomas Bl.

    IO redirecting; waitpid

    Thomas Bl., Aug 16, 2008, in forum: Ruby
    Replies:
    5
    Views:
    268
    Nobuyoshi Nakada
    Aug 18, 2008
  7. Marc Heiler
    Replies:
    1
    Views:
    364
    Robert Klemme
    May 24, 2009
  8. Roger Pack

    Process.waitpid(external pid)

    Roger Pack, Dec 17, 2009, in forum: Ruby
    Replies:
    2
    Views:
    220
    Roger Pack
    Dec 18, 2009
Loading...