Java implementation with a shell redirection or piping commands

Never used java execute shell commands, that is as convenient as C, using a system function can handle that. Today, only to find a use not the case. java inside the shell command execution in two ways:

1. ProcessBuilder

ProcessBuilder pb=new ProcessBuilder(cmd); 
pb.start();

2. Use Runtime

Runtime.getRuntime().exec(cmd)

 But the two methods have a problem, perform functions such as: ps -ef | grep -v grep command with a pipe or redirection error occurs. We all know that execute commands using the above two methods, if you want to command with an argument into an array or List passed, or will be executed as a whole (to be wrong, such as the implementation of "ps -e"). For the |, <,> No, it is not OK to do so. For Linux systems, the solution is to put the entire command are passed as parameters of sh to execute commands sh.

List<String> cmds = new ArrayList<String>(); 
cmds.add("sh"); 
cmds.add("-c"); 
cmds.add("ps -ef | grep -v grep"); 
ProcessBuilder=new ProcessBuilder(cmds); 
Process p = pb.start();

Under Windows the sh into cmd.exe on the line.

Guess you like

Origin blog.csdn.net/yuan1164345228/article/details/90950555