【问题标题】:How do I open STDIN of process in Ruby?如何在 Ruby 中打开进程的 STDIN?
【发布时间】:2011-05-11 05:28:21
【问题描述】:

我有一组需要从 Ruby 脚本运行的任务,但是一个特定的任务总是在退出前等待 STDIN 上的 EOF。

显然这会导致脚本在等待子进程结束时挂起。

我有子进程的进程 ID,但没有管道或任何类型的句柄。如何打开一个进程的 STDIN 句柄来发送 EOF 给它?

【问题讨论】:

    标签: ruby unix process ipc stdin


    【解决方案1】:

    编辑:鉴于您没有启动脚本,我想到的一个解决方案是在使用您的 gem 时将 $stdin 置于您的控制之下。我建议类似:

    old_stdin = $stdin.dup
    # note that old_stdin.fileno is non-0.
    # create a file handle you can use to signal EOF
    new_stdin = File::open('/dev/null', 'r')
    # and make $stdin use it, instead.
    $stdin.reopen(new_stdin)
    new_stdin.close
    # note that $stdin.fileno is still 0, though now it's using /dev/null for input.
    # replace with the call that runs the external program
    system('/bin/cat')
    # "cat" will now exit.  restore the old state.
    $stdin.reopen(old_stdin)
    old_stdin.close
    

    如果您的 ruby​​ 脚本正在创建任务,它可以使用IO::popen。例如,cat,在不带参数运行时,将在标准输入上等待 EOF 退出,但您可以运行以下命令:

    f = IO::popen('cat', 'w')
    f.puts('hello')
    # signals EOF to "cat"
    f.close
    

    【讨论】:

    • 启动这个过程的不是我的脚本,它实际上是一个宝石。我不想编辑gem,所以我需要直接发送EOF。
    猜你喜欢
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2015-12-02
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多