Java executes a problem with a redirect or Pipe shell command __java

Source: Internet
Author: User
The Java Execution Shell command has not been used before, and it is thought to be as convenient as C, and can be done with a system function. It's not that much of a problem today. There are two ways of executing shell commands in Java:
1. Use of Processbuilder
Processbuilder pb=new processbuilder (cmd); 
Pb.start ();
2. Use of runtime
Runtime.getruntime (). EXEC (CMD)

But both of these methods have a problem, such as: Ps-ef | grep-v grep commands with pipes or redirects can be faulted. We all know that using both methods to execute a command, if you have parameters to split the command into a group or list, it will be executed as a whole (error, such as "ps-e"). For |,<,>, this is not going to work either. For Linux systems, the solution is to pass the entire command as an sh parameter and use SH to execute the command.

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 ();
Windows to replace SH cmd.exe on the line.

Ps:linux under test is available, windows you can test yourself

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.