tags:

views:

231

answers:

3

I have a Ruby script that's being used to do some API calls/screen scraping, but our main app is in PHP. Our PHP app is using shell_exec() to call the Ruby script.

The ruby script works great when called from the command line–but it will randomly exits early when called via PHP's shell exec.

Here's an example of the Ruby script:

#!/usr/bin/env ruby
require 'rubygems'
require 'mysql'
require 'net/http'
require 'open-uri'
require 'uri'
require 'cgi'
require 'fileutils'

# Bunch of code here ... works fine 
somePath = 'http://foo.com/bar.php'
# Seems to always exit when I do a Net::HTTP or open-uri call 
post = Net::HTTP.post_form(URI.parse(somePath),{'id'=>ID,'q'=>'some query'})
data = post.body
# OR 
data = open(somePath).read
# More code here ...

So, all I can deduce so far is that it's always exiting when I try to grab/read an external URL via net/http or open-uri calls. The pages I'm grabbing can accept POST or GET requests, but it seems to be exiting either way.

I'm outputting the results with PHP after the shell_exec call, but there are no error messages or exits. I do have messages being output by my Ruby script with "puts ...." here and there. Could that be a problem (I'm thinking 'no' because it doesn't exit with earlier puts messages)?

Again, it works fine when called from the shell. It's almost like the shell_exec call isn't waiting for the net/http call to finish.

Any ideas?

A: 

I'm not sure on this, but given your explanation, which sounds plausible, have you looked at all at proc_open:

http://us3.php.net/proc%5Fopen

John Lockwood
What does proc_open do differently than shell_exec?
Callmeed
A: 

Ruby's open-uri requires tempfile, so I'm guessing there's a file ownership conflict between you running your ruby script and the web server running it. Can the web server create a temp file using tempfile?

glenn jackman
How would I test that? Just see if I can shell_exec() a tempfile command in Ruby?
Callmeed
Ok, I tested with a ruby script that creates a tempfile, sleeps for 60 secs, then closes. I ran it with PHP's shell_exec() and it worked fine. The file showed in /tmp while running. That doesn't seem to be the problem, but I do appreciate the idea. Thanks.
Callmeed
A: 

Just an FYI, I never really uncovered why this was happening. The best I could deduce was that some type of permission issue was preventing Ruby's open-uri commands from working properly.

I opted for queuing these jobs in a db table and running my ruby script via cron periodically. Everything seems to work fine when the ruby script runs with root/sudo perms.

Callmeed