我有一个由用户提交的cpp代码。我的数据库中也有输入和输出文件如何在输入和输出文件上编译和运行此cpp代码。
另外,如何限制上述代码运行的运行时间和内存消耗另外,我如何度量内存的大小以及执行上述代码所需的时间。
编辑我得到下面的黑客工作现在唯一的问题是如何限制运行程序的内存使用如果它能独立于操作系统,我将不胜感激但如果它不可能同时适用于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)

最佳答案

你可以用你的ruby代码创建一些运行脚本,比如run.sh,如果你使用的是类似于*nix的操作系统。
此脚本的上下文将如下所示:

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

其中,timeout程序是这个perl脚本https://github.com/pshved/timeout
如果程序违反时间或内存限制,它将终止程序。
在ruby中,您只需执行run.sh脚本(run.sh)或类似的smth。
对于窗户,你可以用同样的方法

关于ruby-on-rails - 如何通过Ruby on Rails Web服务器进行编译和编码,从而限制CPU和内存的使用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10657579/

10-12 12:51
查看更多