【问题标题】:Is there anything like Python's pty.fork for Ruby?有没有类似 Python 的 pty.fork for Ruby 的东西?
【发布时间】:2011-09-12 20:17:02
【问题描述】:

我正在尝试将如下的一些 Python 代码移植到 Ruby:

import pty

pid, fd = pty.fork
if pid == 0:
  # figure out what to launch
  cmd = get_command_based_on_user_input()

  # now replace the forked process with the command
  os.exec(cmd)
else:
  # read and write to fd like a terminal

因为我需要像终端一样读写子进程,所以我知道我应该使用 Ruby 的 PTY 模块来代替 Kernel.fork。但它似乎没有等效的 fork 方法;我必须将命令作为字符串传递。这是我能得到的最接近 Python 的功能:

require 'pty'

# The Ruby executable, ready to execute some codes
RUBY = %Q|/proc/#{Process.id}/exe -e "%s"|

# A small Ruby program which will eventually replace itself with another program. Very meta.
cmd = "cmd=get_command_based_on_user_input(); exec(cmd)"

r, w, pid = PTY.spawn(RUBY % cmd)
# Read and write from r and w

显然其中一些是特定于 Linux 的,这很好。显然有些是伪代码,但这是我能找到的唯一方法,而且我只有 80% 的把握它无论如何都能工作。 Ruby 肯定有更干净的东西吗?

重要的是“get_command_based_on_user_input()”不会阻塞父进程,这就是我把它卡在子进程中的原因。

【问题讨论】:

  • 您想在子分支中获取 cmd,执行它,然后将终端 fid 返回到主分支?

标签: python ruby linux fork pty


【解决方案1】:

您可能正在寻找http://ruby-doc.org/stdlib-1.9.2/libdoc/pty/rdoc/PTY.htmlhttp://www.ruby-doc.org/core-1.9.3/Process.html#method-c-forkCreate a daemon with double-fork in Ruby

我会用主进程打开一个 PTY,使用 STDIN.reopen 将子进程分叉并重新附加到所述 PTY。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2012-12-19
    • 2011-01-01
    • 2012-10-21
    • 1970-01-01
    相关资源
    最近更新 更多