How would I 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)
Asked
Active
Viewed 127 times
0
-
What about simply running Clang (or, if you want to punish the user with bad error messages, CC) from a Ruby script? What have you tried? – Feb 18 '11 at 19:47
-
3Compiling is easy: just invoke a C compiler. The harder part is making sure you don't run malicious code in your server. – R. Martinho Fernandes Feb 18 '11 at 19:48
-
possible duplicate of [Open Source Programming Language online interpreter](http://stackoverflow.com/questions/3853617/open-source-programming-language-online-interpreter) – zengr Feb 18 '11 at 20:49
1 Answers
0
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.

Sébastien Le Callonnec
- 26,254
- 8
- 67
- 80