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:

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

(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

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.


Also gave this a try:

@stdin =, "r") @stdout =, "w")

And still no luck…