私はruby
オブジェクト指向言語が初めてで、メソッド内でプロセスをフォークし、遅延出力をメソッド外で使用してプロセス ID を返す方法を見つけるのに苦労しています。
def method(arg)
proc_id = fork do
var = `command #{arg}`
end
return both = [proc_id, var]
end
プロセスがまだ終了していないため、これは機能しませvar
ん。nil
どうすればこのようなことを達成できますか?
アップデート:
を使用しIO.pipe
て、プロセス間通信を実現できました。ただし、メソッド内でこのソリューションを使用しようとすると、最初にプロセスが終了するのを待たずに両方を返すことができず、そうでなければ不要な新しい配列と反復を作成する必要がありますproc_id
。var
ここでの目的は、fork
メソッド内のプロセスがまだ機能している間に、メソッド外で自由にコードを実行できるようにすることです。
arg_array = ["arg1", "arg2", "arg3", "arg4"]
input = []
output = []
proc_id = []
arg_array.each_index do |i|
input[i], output[i] = IO.pipe
proc_id[i] = fork do
input[i].close
output[i].write `command #{arg_array[i]}`
end
output[i].close
end
command2
command3
include Process
waitpid(proc_id[0])
command4
Process.waitall
arg_array.each_index do |x|
puts input[x].read
end