16
   Process p = Runtime.getRuntime().exec(command);
   is = p.getInputStream();
   byte[] userbytes = new byte[1024];
   is.read(userbytes);

I want to execute a shell command in linux os from java . But pmd reports says don't use java Runtime.exec(). Why? What is the reason ? Is there any alternative for Runtime.exec()?

4
  • 2
    What message is pmd showing exactly? Commented May 23, 2012 at 15:39
  • Problem description: Do not use Runtime.exec() to execute commands Commented May 23, 2012 at 15:41
  • 2
    This is an absurd statement, with absolutely no backing Commented May 23, 2012 at 15:41
  • What is the reason to avoid executing Runtime.exec() method ? . Is this any injection is possible? Commented May 23, 2012 at 15:43

1 Answer 1

41

Unless you're stuck on an ancient JVM, java.lang.ProcessBuilder makes it much easier to specify a process, set up its environment, spawn it, and handle its file descriptors.

This class is used to create operating system processes.

Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.

...

Starting a new process which uses the default working directory and environment is easy:

 Process p = new ProcessBuilder("myCommand", "myArg").start();

Here is an example that starts a process with a modified working directory and environment:

 ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 pb.directory(new File("myDir"));
 Process p = pb.start();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.