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

ターミナルのようにサブプロセスの読み取りと書き込みを行う必要があるため、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()」が親プロセスをブロックしないことです。そのため、子プロセスでスタックしました。

4

1 に答える 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-forkRuby で double-fork を持つデーモンを作成します

マスター プロセスで PTY を開き、フォークして、STDIN.reopen でその PTY に子を再接続します。

于 2011-11-10T13:30:32.047 に答える