Vincent
Vincent

Reputation: 16216

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?

Upvotes: 32

Views: 11641

Answers (2)

sepp2k
sepp2k

Reputation: 370132

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.

Upvotes: 48

McKay
McKay

Reputation: 12604

I believe Process.Fork forks the current process, and Process.Spawn spawns a new process. They are quite different. Do you want a new thread or a new process?

Upvotes: 0

Related Questions