Search code examples
python-3.xubuntugccinfinite-loop

how to protect C file from entering into infinite-loop in ubunto


Im currently writing a python3 script that checks out a C source file by running the C code with various of input files. the compilation is done by GCC if it matters. in some case, the C code enters into an infinite loop (I figured it out because I ran out of memory). is there a way that I can "protect" my code like a watchdog or something that tells me a after X minutes that I ran into an infinite loop?

I cant assume anything about the input so i cant have answers like change it or something...

#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]))

Solution

  • I figured out a way to avoid enter infinite loop by this 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