【问题标题】:how to protect C file from entering into infinite-loop in ubunto如何在ubuntu中保护文件不进入无限循环
【发布时间】:2018-03-26 21:07:27
【问题描述】:

我目前正在编写一个 python3 脚本,该脚本通过运行具有各种输入文件的 C 代码来检查 C 源文件。如果重要,编译由 GCC 完成。 在某些情况下,C 代码进入无限循环(我想通了,因为内存不足)。 有没有办法像看门狗或其他东西一样“保护”我的代码 在 X 分钟后告诉我我遇到了无限循环?

我不能假设任何关于输入的事情,所以我无法得到答案,比如改变它或其他什么......

#runfile is an exe file, code file is .c file, inputlist/outputlist are directories

import subprocess as sbp
import os

sbp.call('gcc -o {0} {1}'.format(runfile,codefile), shell = True)
for i in range(numoFiles):
    #run the file with input i and save it to output i in outdir
    os.system("./{0} <{1} >{2}".format(ID,inputList[i],outputList[i]))

【问题讨论】:

标签: python-3.x ubuntu gcc infinite-loop


【解决方案1】:

查找"Halting Problem"。无法确定任意程序是否最终会结束,或者是否会永远陷入循环。

【讨论】:

  • 虽然这在理论上是正确的,但 OP 实际上是在寻求一种在指定时间后或消耗特定内存量时停止运行代码的方法。
  • 完全是三人组。有办法吗?
【解决方案2】:

我想出了一个避免通过这个method进入无限循环的方法:

import subprocess

for i in range(numofiles):
    cmd="gcc -o {0} {1}".format(runfile,codefile)
    subprocess.call(cmd, shell = True)
    try:
        cmd="./{0} <{1} >'/dev/null'".format(Cfile,inputfile) #check if runtime>100 sec
        subprocess.run(cmd,shell=True,timeout=100)
    except subprocess.TimeoutExpired:
        print("infinite loop")
        continue
    cmd="./{0} <{1} >{2}".format(Cfile,inputfile,outputfile)
    subprocess.run(cmd,shell=True) #print output to txt file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    相关资源
    最近更新 更多