次のような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
ターミナルのようにサブプロセスの読み取りと書き込みを行う必要があるため、Kernel.forkの代わりにRubyのPTYモジュールを使用する必要があることを理解しています。しかし、同等のフォークメソッドはないようです。コマンドを文字列として渡す必要があります。これは、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()」が親プロセスをブロックしないことです。そのため、子プロセスでスタックしました。