我正在尝试获取linux机器的运行服务。我已经打印了它们,但我只想获得服务名称。我的代码:
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();
}
}我将以这种格式获得结果:
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但我希望是这样的:
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我该如何解析它呢?提前谢谢。
发布于 2012-03-09 15:31:03
获取字符串行的长度,并将字符从IndexOf(length-1)返回到第一个空格。
发布于 2012-03-09 15:28:02
我会用man ps查看ps参数,而不是解析输出。
从那里你可以看到一个用户定义输出的部分;
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 对于您的情况,运行这将是答案;
ps -eo comm发布于 2012-03-09 15:38:37
Java风格:
while ((line = input.readLine()) != null) {
String[] split = line.split(" ");
System.out.println(split[split.length-1]);
}https://stackoverflow.com/questions/9630349
复制相似问题