[英]Getting running services (LINUX JAVA): how to parse service name only?
I am trying to get the running services of a linux machine. 我正在尝试获取linux机器的运行服务。 I have printed them but I want to get the service name only.
我已经打印了它们,但是我只想获得服务名称。 My code:
我的代码:
public void runningservices()
{
try {
String line;
Process p = Runtime.getRuntime().exec("ps -e");
BufferedReader input =
new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); //<-- Parse data here.
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}
I am getting the result in this format: 我得到这种格式的结果:
PID TTY TIME CMD
1 ? 00:00:46 init
2 ? 00:00:00 migration/0
3 ? 00:00:00 ksoftirqd/0
4 ? 00:00:00 watchdog/0
5 ? 00:00:00 events/0
6 ? 00:00:00 khelper
7 ? 00:00:00 kthread
9 ? 00:00:00 xenwatch
10 ? 00:00:00 xenbus
12 ? 00:00:05 kblockd/0
13 ? 00:00:00 kacpid
176 ? 00:00:00 cqueue/0
180 ? 00:00:00 khubd
182 ? 00:00:00 kseriod
246 ? 00:00:00 khungtaskd
247 ? 00:00:00 pdflush
248 ? 00:00:01 pdflush
249 ? 00:00:00 kswapd0
250 ? 00:00:00 aio/0
457 ? 00:00:00 kpsmoused
485 ? 00:00:00 mpt_poll_0
486 ? 00:00:00 mpt/0
487 ? 00:00:00 scsi_eh_0
490 ? 00:00:00 ata/0
491 ? 00:00:00 ata_aux
496 ? 00:00:00 kstriped
505 ? 00:00:00 ksnapd
516 ? 00:00:12 kjournald
547 ? 00:00:00 kauditd
580 ? 00:00:03 udevd
1865 ? 00:00:00 kmpathd/0
1866 ? 00:00:00 kmpath_handlerd
1925 ? 00:00:00 kjournald
But I want it like this: 但我想要这样:
init
migration
ksoftirqd
watchdog
events
khelper
kthread
xenwatch
xenbus
kblockd
kacpid
cqueue
khubd
kseriod
khungtaskd
pdflush
pdflush
kswapd0
aio
kpsmoused
mpt_poll_0
mpt
scsi_eh_0
ata
ata_aux
kstriped
ksnapd
kjournald
kauditd
udevd
kmpathd
kmpath_handlerd
kjournald
How would I parse it? 我将如何解析? Thanks in advance.
提前致谢。
Instead parsing the output, I would look ps
arguments with man ps
. 代替解析输出,我将使用
man ps
查找ps
参数。
From there you can see a section for user defined outputs; 从那里可以看到用户定义输出的一部分。
To see every process with a user-defined format:
ps -eo pid,tid,class,rtprio,ni,pri,psr,pcpu,stat,wchan:14,comm
ps axo stat,euid,ruid,tty,tpgid,sess,pgrp,ppid,pid,pcpu,comm
ps -eopid,tt,user,fname,tmout,f,wchan
For your situation, running this would be the answer; 对于您的情况,运行此方法将是答案。
ps -eo comm
取串线的长度和从的IndexOf(长度-1)高达第一空间向后获得的字符。
Java style : Java风格:
while ((line = input.readLine()) != null) {
String[] split = line.split(" ");
System.out.println(split[split.length-1]);
}
将命令更改为
ps -e | awk '{print $4}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.