23tux
23tux

Reputation: 14736

Share variable through ruby processes

I'm writing a gem, where I have to fork two processes which are starting two webrick servers. I want to start this servers through a class method from a base class, because there should only be this two servers running, not multiple ones. During runtime, I want to call some methods on this two servers to change variables.

My problem is, that I can't access the instance variables of the forks, through a class method of the base class. Furthermore, I can't use threads inside my base class, because under the hood I'm using another library which is not thread safe. So I have to fork each server to it's own process.

I tried it with class variables, like @@server. But when I try to access this variables through the base class, it's nil. I read that sharing class variables among forks isn't possible in Ruby, am I right?

So, is there any other way around this? I thought of using a singleton, but I'm not sure if this is the best idea.

Upvotes: 6

Views: 2502

Answers (1)

jbr
jbr

Reputation: 6258

When you fork a process then the child and parent processes's memory are separated, so you cannot share variables between them directly. So a singleton class will not work in your case.

The solution is IPC, Ruby supports both pipes and sockets, which are the two most used forms of IPC, at least on *NIX. Ruby also supports distributed objects, if you need a more transparent interface.

What you chose depends on the job. If you know you want to split you processes over several computers at some point, go with sockets or drb. If not go with pipes.

Here's a short introduction to pipes in Ruby

Upvotes: 9

Related Questions