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. Advertising

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. spawnl and waitpid

    , Feb 27, 2007, in forum: Python
    Replies:
    13
    Views:
    764
  2. lasek

    Fork + Waitpid

    lasek, May 13, 2005, in forum: C Programming
    Replies:
    4
    Views:
    5,999
    SM Ryan
    May 14, 2005
  3. Mike

    'waitpid' query

    Mike, Jan 28, 2009, in forum: C Programming
    Replies:
    10
    Views:
    570
    Kenny McCormack
    Jan 29, 2009
  4. Fan
    Replies:
    1
    Views:
    353
    Christopher Head
    Jul 16, 2011
  5. Roger Pack

    Process.waitpid(external pid)

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

Share This Page