My current solution looks like this:
Enter code:
@RequestMapping("/student/runITask.action") public String student_runITask(@ModelAttribute(value = "program") ProgramToCompile program, ModelMap map) { //1. code compile ITaskCompile itcompile = new ITaskCompile(); List<String> errorList = itcompile.compileTask(program.getClassname(), program.getProgram()); Date tmp = new Date(); this.setPathName(program.getClassname() + tmp.hashCode()); //2. if compiled... if (errorList.size() < 1) { try { String[] cmd = {"/bin/sh", "-c", "java -Xmx16M -Xms2M -cp /root/ " + program.getClassname() + "> " + getPathName() + ".data"}; Runtime rt = Runtime.getRuntime(); final Process proc = rt.exec(cmd); Thread.sleep(1000); proc.destroy(); if (proc.exitValue() > 0) { try { killJavaProcesses(); map.addAttribute("comment", "Endless LOOP!"); } catch (Exception ex1) { Logger.getLogger(CompileITaskControler.class.getName()).log(Level.SEVERE, null, ex1); } } else { StringBuffer fileData = new StringBuffer(1000); BufferedReader reader = new BufferedReader(new FileReader("/root/" + getPathName() + ".data")); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { fileData.append(buf, 0, numRead); } reader.close(); map.addAttribute("comment","Output: <br/><br/><br/><pre>"+fileData.toString()+"</pre>"); } } catch (Exception ex) { try { killJavaProcesses(); map.addAttribute("comment", "Endless LOOP!"); } catch (Exception ex1) { Logger.getLogger(CompileITaskControler.class.getName()).log(Level.SEVERE, null, ex1); } } } else { map.addAttribute("errorList", errorList); map.addAttribute("comment", "PROGRAM NIE ZOSTAΕ URUCHOMIONY"); } //3. return return DISPLAY_COMP_MSG; }
where killJavaProcesses () looks like this
public void killJavaProcesses() throws IOException, InterruptedException { String[] getProcessList = {"/bin/sh", "-c", "ps | grep java"}; String[] killProcessByIdList = {"/bin/sh", "-c", "kill -9 "}; Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(getProcessList); InputStream inputstream = proc.getInputStream(); InputStreamReader inputstreamreader = new InputStreamReader(inputstream); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); String line2; String kill = new String(); while ((line2 = bufferedreader.readLine()) != null) { kill += line2 + "\n"; } proc.destroy(); String arraykill[] = kill.split("\n"); String element2kill = ""; String[] tmp; if (arraykill.length >= 1) { element2kill = arraykill[arraykill.length - 1].trim().split(" ")[0]; } killProcessByIdList[2] += element2kill; Process proc2 = rt.exec(killProcessByIdList); proc2.waitFor(); }
I can not kill the process to others. Using proc.destroy () does not work directly on Ubuntu / Win XP machines. Now I will try to configure and use the SecurityManager .
tzim
source share