Ruby - Writing to STDOUT to Asterisk in response to an AGI

I am attempting to author a class that interacts with Asterisk via a standard AGI. Asterisk receives a call, makes a request to an external Ruby script via STDIN, and then the external Ruby scripts issues commands via STDOUT and receives the response via STDIN.

I am able to receive the initial set of paramters that Asterisk sends to my Ruby script via STDIN as follows:

  protected
  def getInitialParams()
   @initial_params = Hash.new
   $stdin.each do | line |
     if line.length <= 1
      break
     end
     line = line.split(":")
     line[0] = line[0].rstrip
     line[1] = line[1].to_s.strip
     @initial_params["#{line[0]}"] = line[1]
   end
   @log.debug("initial params: #{@initial_params['agi_request']}")
  end

(Any recommendations on building a Hash based on STDIN welcome.)

But, when I try to write a command:

  def astCommand(command)
   # Must be 'puts' to standard out as Asterisk requres a newline for commands
   $stdout.puts command
   @log.debug("After command puts")
   result = $stdin.gets
   return result
  end

Nothing appears to be returned to Asterisk and it ‘hangs’ waiting for the command (only returns one line in this case as opposed to multiple at initialization).

If I run my script at the command line and interact with it there, STDIN/STDOUT work fine and as expected.

I am able to interact via STDIN/STDOUT with Asterisk via PHP.

I have also tried the following without using $stdout with the same result:

On a side note, ‘puts’ does put a newline “\n” after the command.

Ideas?

Also gave this a try:

@stdin = IO.open(0, "r") @stdout = IO.open(1, "w")

And still no luck…