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

Vincent picture Vincent · Nov 9, 2010 · Viewed 10.7k times · Source

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?

Answer

sepp2k picture sepp2k · Nov 9, 2010

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.