Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 288
23tux Avatar asked May 14 '13 08:05

23tux


People also ask

Do parent and child process share variables?

Recall that when a process forks, the new child process has an identical copy of the variables of the parent process. After fork the parent and child can update their own copies of the variables in their own way, since they dont actually share the variable.

When to use global variables in Ruby?

If we want to have a single variable, which is available across classes, we need to define a global variable.

What is a global variable Ruby?

Global Variables are variables that may be accessed from anywhere in the program regardless of scope. They're denoted by beginning with a $ (dollar sign) character. However, the use of global variables is often considered "un-Ruby," and you will rarely see them.

How do variables work in Ruby?

A variable is a label, or a container used to store data in a Ruby program. Each variable in a program has a unique name and a value that it holds. Variables in Ruby points to an object. Hence, when assigning a variable, you assign the object referenced by the variable.


1 Answers

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

like image 86
jbr Avatar answered Sep 29 '22 15:09

jbr