Running a bash script / program with limited resources

I use a tool to create PDF files, which, unfortunately, is not 100% reliable. Sometimes this tool gets into an infinite loop and consumes 100% of memory and processor.

I run this tool from my Java application using Runtime.getRuntime.exec("command") .

  • Is there a way to set the maximum runtime / memory for this process directly in the Java command?
  • If not directly from Java, is there a way to wrap the command in some bash tool that will limit resources?

I prefer the team to fail than use all the resources and basically kill the server.

EDIT

Based on ulimit suggestions, I try this:

 Runtime.getRuntime() .exec(arrayOf("bash", "-c", "ulimit -m 2; ulimit -a; pdfprint")) 

I see ulimit working:

 core file size (blocks, -c) 0 data seg size (kbytes, -d) unlimited file size (blocks, -f) unlimited max locked memory (kbytes, -l) unlimited max memory size (kbytes, -m) 2 open files (-n) 10240 pipe size (512 bytes, -p) 1 stack size (kbytes, -s) 8192 cpu time (seconds, -t) unlimited max user processes (-u) 709 virtual memory (kbytes, -v) 2 

The strange thing is that I expected pdfprint to crash because it would pdfprint out of memory. However, this does not happen, and the program works correctly.

+5
source share
2 answers

The best solution is to edit the bash script and add restrictions.

You can limit the use of bash Script memory by following these steps.

Limit memory usage with kb (2GB in this example):

 ulimit -m 2048000 

Limit on virtual memory usage:

 ulimit -v 2048000 

Set the virtual memory limit as a hard limit so that the process is killed when this limit is exceeded:

 ulimit -H -v 

To limit the CPU, you can use the cpulimit tool

+2
source

I don't know if Runtime is required for you, but it was used with java JDK <5, then ProcessBuilder . With ProcessBuilder you can combine Process and waitFor (..) . From java 8, they introduced parameters to this method.

Looks like (taken from the original manual):

 boolean waitFor(long timeout, TimeUnit unit) 

Causes the current thread to wait, if necessary, until the subprocess represented by this Process object has stopped or the specified timeout has expired.

The following is an example of pseudo code that shows how it works:

 ProcessBuilder pb = new ProcessBuilder("command"); Process p = pb.start(); p.waitFor(...); 
+1
source

Source: https://habr.com/ru/post/1270476/


All Articles