有没有像 Python 的 Ruby 的 pty.fork 之类的东西?

bio*_*net 5 ruby python linux fork pty

我正在尝试将如下所示的 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
Run Code Online (Sandbox Code Playgroud)

由于我需要像终端一样读取和写入子进程,我明白我应该使用 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
Run Code Online (Sandbox Code Playgroud)

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

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

Slo*_*tos 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-fork在 Ruby 中创建一个带有双叉的守护进程

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