![“ps -ef | grep java”使用 java 程序](https://linux22.com/image/1375042/%E2%80%9Cps%20-ef%20%7C%20grep%20java%E2%80%9D%E4%BD%BF%E7%94%A8%20java%20%E7%A8%8B%E5%BA%8F.png)
ps -ef | grep java
我正在尝试通过 Java 程序执行。这是我的代码-
// String sudoScript = "sh -c \"ps -ef | grep java\"";
String sudoScript = "ps -ef | grep java";
try {
System.out.println("command=" + sudoScript);
Process p1 = Runtime.getRuntime().exec(sudoScript);
System.out.println("exit code: "+p1.waitFor());
FileInputStream fis1 = (FileInputStream) p1.getErrorStream();
int content1;
while ((content1 = fis1.read()) != -1) {
// convert to char and display it
System.out.print((char) content1);
}
BufferedReader stdInput1 = new BufferedReader(
new InputStreamReader(p1.getInputStream()));
while ((sudoScript = stdInput1.readLine()) != null) {
System.out.println(sudoScript);
}
} catch (Exception e) {
e.printStackTrace();
}
这是我执行命令时得到的输出ps -ef | grep java
-
command=ps -ef | grep java
exit code: 1
ERROR: Garbage option.
********* simple selection ********* ********* selection by list *********
-A all processes -C by command name
-N negate selection -G by real group ID (supports names)
-a all w/ tty except session leaders -U by real user ID (supports names)
-d all except session leaders -g by session OR by effective group name
-e all processes -p by process ID
T all processes on this terminal -s processes in the sessions given
a all w/ tty, including other users -t by tty
g OBSOLETE -- DO NOT USE -u by effective user ID (supports names)
r only running processes U processes for specified users
x processes w/o controlling ttys t by tty
*********** output format ********** *********** long options ***********
-o,o user-defined -f full --Group --User --pid --cols --ppid
-j,j job control s signal --group --user --sid --rows --info
-O,O preloaded -o v virtual memory --cumulative --format --deselect
-l,l long u user-oriented --sort --tty --forest --version
-F extra full X registers --heading --no-heading --context
********* misc options *********
-V,V show version L list format codes f ASCII art forest
-m,m,-L,-T,H threads S children in sum -y change -l format
-M,Z security data c true command name -c scheduling class
-w,w wide output n numeric WCHAN,UID -H process hierarchy
我尝试使用sh -c "ps -ef | grep java"
。但没有成功。得到以下输出-
command=sh -c "ps -ef | grep java"
exit code: 1
-ef: -c: line 0: unexpected EOF while looking for matching `"'
-ef: -c: line 1: syntax error: unexpected end of file
我该如何克服这个问题?
答案1
找到它了!对我有用。
try {
Process p1 = Runtime.getRuntime().exec(new String[] { "ps", "-ef" });
InputStream input = p1.getInputStream();
Process p2 = Runtime.getRuntime().exec(new String[] { "grep", "java"});
OutputStream output = p2.getOutputStream();
IOUtils.copy(input, output);
output.close(); // signals grep to finish
List<String> result = IOUtils.readLines(p2.getInputStream());
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}