【发布时间】: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