开发者

Compiling c using ruby

How would I 开发者_JAVA技巧go about making a Website like codepad? Essentially I want to be able to compile C code after a user types it in and out put the success or error message. If it is successful, how would I be able to run it with certain parameters? (This is for a coding competition site)


You can call the C compiler from the ruby code by using the backticks. Here is a quick and dirty example with Sinatra:

require 'sinatra'
# Display HTML form
get '/code' do
  '<html><form method="post"><textarea name="code"></textarea><input type="submit" /></form></html>'
end

# Compile code
post '/code' do
  exec = "gcc -x c -o tst - <<EOF\n#{params[:code]} \nEOF\n"
  `#{exec}`
end

When calling http://localhost:4567, a form appears where you can enter your C code. When you press submit, the code is then compiled to the tst executable.

You can then use the backticks to execute tst with whatever parameters you want, similar to what is done for the compilation process itself.

The stdin output can be captured by storing the result of the backtick command in a variable, e.g.:

output = `tst`

stderr can be captured by redirecting to stdin, e.g.:

output = `tst 2>&1`

NB: Please be careful though, from a security perspective, this is very very dangerous: anyone can submit any C code, and get it to compile and execute on your server.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜