2012-05-18 15 views
2

我有一個用戶提交的cpp代碼。我也有輸入和輸出文件在我的分貝。如何在輸入和輸出文件上編譯和運行這個cpp代碼。如何從Ruby on Rails Web服務器編譯和編寫代碼,限制CPU和內存使用量?

此外,如何限制上面運行代碼的運行時間和內存消耗。另外我該如何測量內存的存儲量以及執行上述代碼需要多少時間。

編輯我在下面的黑客工作。現在唯一的問題是如何限制正在運行的程序的內存使用情況。我將不勝感激,如果它將獨立於操作系統。但是,如果它不適用於Windows和Linux的解決方案是受歡迎的。

需要 '超時'

runDir = 'run\\' 

    def code_file(sid) 
     return "#{sid}.cpp" 
    end 

    def executable_file(sid) 
     return "#{sid}.exe" 
    end 

    def input_file(sid) 
     return "#{sid}.in" 
    end 

    def output_file(sid) 
     return "#{sid}.out" 
    end 

    def get_complie_command_line(sid , runDir) 
     return "g++ -w -O2 #{code_file(sid)} -o #{runDir}#{executable_file(sid)}" 
    end 

    def get_run_command_line(sid , runDir) 
     return "#{runDir}#{executable_file(sid)} < #{sid}.in" 
    end 

    def run_submission(sid , runDir) 
     begin 
     timeout(5) { 
      run_cmd_line = get_run_command_line(1 , runDir) 
      puts run_cmd_line 
      runOutput = %x[#{run_cmd_line}] 
      puts runOutput 
     } 
     puts "Timeout didn't occur" 
     rescue Timeout::Error  
      puts "Timed out!" 
     end 
    end 

    def compile(sid , runDir) 
     #make the directory 
     %x[mkdir #{runDir}] 

     #get compile command line and produce the exe 
     cmd_line = get_complie_command_line(1 , runDir) 
     puts cmd_line 
     compile_error = %x[#{cmd_line}].to_s.strip 

     #run the code 
     if compile_error.length != 0 
      puts "Compile Errors" 
     else 
      run_submission(1 , runDir) 
     end 
    end 



    compile(1 , runDir) 
+3

您是否知道如何手動執行所有操作?作爲@SergioTulentsev的 –

+1

表示你應該首先知道如何手動執行該操作,那麼你的問題只是讓ruby執行那些命令。 –

+0

是的,我知道如何手動。我會g ++ -o 1.cpp 1.out和1.out < 1.in > 1.out並將這個1.out文件與我有的輸出文件進行比較。但現在我無法限制時間和內存的使用。另外我知道必須有更好的辦法,而不僅僅是在ruby中運行命令。也許需要另一個流程來完成這項工作。 –

回答

0

您可以創建一些運行腳本Ruby代碼,說run.sh如果你使用的* nix-like操作系統。 這個腳本的內容將會是水木清華這樣的:

#!/bin/bash 
/path/to/timeout /path/to/your/compiled/cpp/program </your/stdin> /your/stdout 

凡超時程序是這樣的perl腳本https://github.com/pshved/timeout 如果違反時間或內存限制它會殺了你的程序。 從ruby開始,你只需要執行run.sh腳本(run.sh)或者像這樣。 對於Windows,您可以使用相同的aproach