0

私はrubyオブジェクト指向言語が初めてで、メソッド内でプロセスをフォークし、遅延出力をメソッド外で使用してプロセス ID を返す方法を見つけるのに苦労しています。

def method(arg)
    proc_id = fork do
        var = `command #{arg}`
    end
    return both = [proc_id, var]
end

プロセスがまだ終了していないため、これは機能しませvarん。nilどうすればこのようなことを達成できますか?

アップデート:

を使用しIO.pipeて、プロセス間通信を実現できました。ただし、メソッド内でこのソリューションを使用しようとすると、最初にプロセスが終了するのを待たずに両方を返すことができず、そうでなければ不要な新しい配列と反復を作成する必要がありますproc_idvarここでの目的は、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
4

3 に答える 3

0

jaeheungの提案のおかげで、 Open3.popen2(バージョン 1.9.3 が必要)を使用して解決しました。

arguments = ["arg1", "arg2", "arg3", "arg4"]
require 'open3'
include Open3
def method(arg)
    input, output, thread = Open3.popen2("command #{arg}")
    input.close
    return [thread.pid, output]
end
thread_output = []
arguments.each do |i|
    thread_output << method("#{i}")
end
command1
command2
include Process
waitpid(thread_output[0][0])
command3
Process.waitall
thread_output.each do |x|
    puts x[1].read
end
于 2013-11-15T09:32:45.393 に答える
0

何かを開始して子 pid を保存したい場合、それはかなり簡単です。

pid = fork
if pid
    return pid
else
    system("command #{arg}")
    exit
end

少し不器用ですが、基本的にforkは、子 pid を親プロセスと子プロセスに返しますnil。必ず子を終了してください。自動的には終了しません。

于 2013-11-13T18:08:31.840 に答える