11

I have to run a command in the background but I want to have proper escaping for its parameter.

system("rake send_mails subject='#{params[:subject]}' 2> /dev/null 1> /dev/null &");

If I write system("rake", "send_mails", params[:subject]) then I don't have "place" for redirections and the & sign. If I don't I do not have escaping for the subject parameter.

How can I resolve this?

2
  • I am not sure, but did you try to nest system calls? For example: system(system("rake", "send_mails", params[:subject]), "/dev/null 1> /dev/null &") Commented May 10, 2011 at 11:11
  • The inner system() call is executed then the outer system() fails without executing anything: TypeError: can't convert true into String Commented May 10, 2011 at 11:24

1 Answer 1

20

In Ruby 1.9, try Process.spawn:

# Spawn a new process and run the rake command
pid = Process.spawn({"subject" => params[:subject]},
                    "rake", "send_mails",
                    :out => 'dev/null', :err => 'dev/null')

# Detach the spawned process
Process.detach pid
Sign up to request clarification or add additional context in comments.

7 Comments

The point would be not to wait at all. We have to move on to processing the next web query - as I failed to mention it. But that's the point in redirecting the output to /dev/null and running with & - to reach complete detachment.
Then use Process.detach after you've spawned the new process. I will edit my answer to include this.
Adding that Process.fork do ... end is available and close-to-perfect in 1.8.7.
But I am still hungry for a function like PHP's escapeshellarg().
I know it has been a while, but there is Shellwords: stackoverflow.com/questions/5949008/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.