Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Process.fork and Process.spawn in Ruby 1.9.2

What's the difference between Process.fork and the new Process.spawn methods in Ruby 1.9.2 and which one is better to run another program in a subprocess? As far as I understand Process.fork accepts block of code and Process.spawn takes a system command plus some other parameters. When I should use one instead of the other?

like image 935
Vincent Avatar asked Nov 08 '10 23:11

Vincent


1 Answers

What's the difference between Process.fork and the new Process.spawn methods in Ruby 1.9.2

Process.fork allows you to run ruby code in another process. Process.spawn allows you to run another program in another process. Basically Process.spawn is like using Process.fork and then calling exec in the forked process, except that it gives you more options.

and which one is better to run another program in a subprocess?

If you need backwards compatibility, use fork + exec as spawn is not available in 1.8. Otherwise use spawn since running another program in a subprocess is exactly what spawn is made for.

As far as I understand Process.fork accepts block of code and Process.spawn takes a system command plus some other parameters.

Exactly.

When I should use one instead of the other?

Use fork if you need to run arbitrary ruby code in a separate process (you can't do that with spawn). Use spawn if you need to invoke an application in a subprocess.

like image 178
sepp2k Avatar answered Sep 22 '22 23:09

sepp2k