Reputation: 331
I am trying to get the running services of a linux machine. 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.
Upvotes: 2
Views: 1990
Reputation: 73
Java style :
while ((line = input.readLine()) != null) {
String[] split = line.split(" ");
System.out.println(split[split.length-1]);
}
Upvotes: 1
Reputation: 1746
Take the length of the string line and get the characters backward from IndexOf(length-1) upto the first space.
Upvotes: 2
Reputation: 1364
Instead parsing the output, I would look ps
arguments with man 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
Upvotes: 2