Search code examples
rubydaemondaemons

How to run multiple ruby daemons and handle input and output of each daemon?


Here's the code:

while 1
    input = gets
    puts input
end

Here's what I want to do but I have no idea how to do it: I want to create multiple instances of the code to run in the background and be able to pass input to a specific instance.

Q1: How do I run multiple instances of the script in the background?

Q2: How do I refer to an individual instance of the script so I can pass input to the instance (Q3)?

Q3: The script is using the cmd "gets" to take input, how would I pass input into an indivdual's script's gets?

e.g

Let's say I'm running threes instances of the code in the background and I refer to the instance as #1, #2, and #3 respectively. I pass "hello" to #1, #1 puts "hello" to the screen. Then I pass "world" to #3 and #3 puts "hello" to the screen.

Thanks!

UPDATE: Answered my own question. Found this awesome tut: http://rubylearning.com/satishtalim/ruby_threads.html and resource here: http://www.ruby-doc.org/core/classes/Thread.html#M000826.

puts Thread.main

x = Thread.new{loop{puts 'x'; puts gets; Thread.stop}}
y = Thread.new{loop{puts 'y'; puts gets; Thread.stop}}
z = Thread.new{loop{puts 'z'; puts  gets; Thread.stop}}

while x.status != "sleep" and y.status != "sleep" and z.status !="sleep"
    sleep(1)
end

Thread.list.each {|thr| p thr }

x.run
x.join

Thank you for all the help guys! Help clarified my thinking.


Solution

  • I assume that you mean that you want multiple bits of Ruby code running concurrently. You can do it the hard way using Ruby threads (which have their own gotchas) or you can use the job control facilities of your OS. If you're using something UNIX-y, you can just put the code for each daemon in separate .rb files and run them at the same time.

    E.g.,

    # ruby daemon1.rb &
    # ruby daemon2.rb &
    

    There are many ways to "handle input and output" in a Ruby program. Pipes, sockets, etc. Since you asked about daemons, I assume that you mean network I/O. See Net::HTTP.