5

我正在尝试将一些 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()”不会阻塞父进程,这就是我将它卡在子进程中的原因。

4

1 回答 1

1

You're probably looking for http://ruby-doc.org/stdlib-1.9.2/libdoc/pty/rdoc/PTY.html, http://www.ruby-doc.org/core-1.9.3/Process.html#method-c-fork and Create a daemon with double-fork in Ruby.

I'd open a PTY with master process, fork and reattach child to said PTY with STDIN.reopen.

于 2011-11-10T13:30:32.047 回答