Ruby中有没有类似Python的pty.fork的东西?

5 投票
1 回答
629 浏览
提问于 2025-04-17 02:08

我正在尝试把一些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。不过,PTY模块似乎没有和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()”不能阻塞父进程,这就是我把它放在子进程里的原因。

1 个回答

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来实现。

撰写回答