Processing daemon input and output

I want to create a ruby ​​program daemon on Linux.

I also want the daemon to be interactive - I want to be able to send input to the daemon via file / pipe / the easiest method and get output to the file.

How can I do it?

I looked at the module daemons (http://daemons.rubyforge.org/), streams, and the popen3 method, but it's not easy for me to get them to do this.

ANSWER: Mladen Method:

I have a controller that creates a demon: (you will need the pearl of the demon module)

require 'rubygems' require 'daemons' Daemons.run('/myDaemon.rb', {:app_name => "o", :dir_mode => :normal, :dir => '', :log_output => true, :multiple => true }) 

Here is myDaemon.rb:

 puts `pwd` File.open('my_pipe', 'r+') do |f| loop do line = f.gets puts "Got: #{line}" end end 

Steps: Both files are in my root directory \. Daemons.run creates a daemon in \.

  • Create a named pipe, mkfifo./my_pipe.

  • ruby controller.rb start

  • cat> my_pipe

  • enter text

  • ctrl-c to stop input

  • cat o.output to see your output

+4
source share
2 answers

Probably the easiest way, called pipe, based on http://www.pauldix.net/2009/07/using-named-pipes-in-ruby-for-interprocess-communication.html :

Step 1: Create a Named Channel

 mkfifo ./my_pipe 

Step 2. Create your “daemon":

 File.open('my_pipe', 'r+') do |f| loop do line = f.gets puts "Got: #{line}" end end 

and run it.

Step 3: Open another terminal and run

 cat > my_pipe 

and start typing on a line.

Step 4. Watch the demon exit.

Step 5:

Step 6: Profit.

+4
source

Open the socket associated with a port that is not in use, but that you know of and the program (s) that want to communicate with it. If the daemon only needs to talk to processes on the same computer, then use a Unix domain socket (see Socket.unix_server_loop ). If he also needs to interact with processes outside the host on which he is running, you need to open an Internet socket (see Socket.tcp_server_loop ).

General recipe for the server:

  • Open socket
  • Bind to host IP address and selected port (tcp) or bind to system path (unix)
  • Wait (select) to connect
  • Accept connection
  • Enter read / write communication loop

On the client:

  • Open socket
  • Connect to the server address / port or connect to the Unix socket path that the server uses
  • After connecting, enter the write / record link cycle.

Your server and client (s) need to agree who sends what comes first and which corresponding responses belong to the other side.

+2
source

All Articles