0

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]))
Yoni Newman
  • 185
  • 13
  • 1
    [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) please . Show the blueprint of your code. – Morse Mar 26 '18 at 21:21
  • Why are you using `os.system` as well when you have already figured out how to use `subprocess.call`? – tripleee Mar 27 '18 at 05:22
  • Possible duplicate of [Using module 'subprocess' with timeout](https://stackoverflow.com/questions/1191374/using-module-subprocess-with-timeout) – tripleee Mar 27 '18 at 06:03
  • tripleee, Its a part of a bigger script so untill i figured out how to use subprocess I used os instead.. I'll change it.. – Yoni Newman Mar 27 '18 at 07:46

2 Answers2

0

Look up the "Halting Problem". It is not possible to determine whether an arbitrary program will eventually finish or if it will be stuck in a loop forever.

Thomas English
  • 231
  • 1
  • 8
  • While this is theoretically true, the OP is actually asking for a way to stop running the code after a specified amount of time or when it consumes a particular amount of memory. – tripleee Mar 27 '18 at 05:21
  • exactly tripleee. is there a way to do so? – Yoni Newman Mar 27 '18 at 07:47
0

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
Yoni Newman
  • 185
  • 13