Ruby processes: Difference between revisions
From wikinotes
(→Spawn) |
(→Fork) |
||
Line 46: | Line 46: | ||
Fork allows you to run ruby code in a separate process.<br> | Fork allows you to run ruby code in a separate process.<br> | ||
< | <syntaxhighlight lang="ruby"> | ||
pid = Process.fork do | pid = Process.fork do | ||
puts "child, pid #{Process.pid} sleeping..." | puts "child, pid #{Process.pid} sleeping..." | ||
Line 54: | Line 54: | ||
Process.wait pid | Process.wait pid | ||
</ | </syntaxhighlight> | ||
https://naturaily.com/blog/multiprocessing-in-ruby | https://naturaily.com/blog/multiprocessing-in-ruby |
Revision as of 17:27, 29 October 2022
Documentation
Process docs https://docs.ruby-lang.org/en/2.7.0/Process.html
Subprocesses
Process functions create/operate on a PID (instead of an object representing the process, like python).
Backticks
`ls -la | grep foo` puts "exit code is 0" if $?.successSpawn
pid = Process.spawn(['ls', '-la']) puts pid # 123456 Process.wait pidManipulating STDIN, STDOUT, STDERR.
# STDIN from file Process.spawn("/usr/bin/cat", in: File.open("/home/you/.zshrc", "r")) # STDIN from string r_pipe, w_pipe = IO.pipe w_pipe.write("a\nb\nc") w_pipe.close Process.spawn("/usr/bin/cat", in: r_pipe) r_pipe.close
Fork
Fork allows you to run ruby code in a separate process.
pid = Process.fork do
puts "child, pid #{Process.pid} sleeping..."
sleep 5
puts "child exiting"
end
Process.wait pid