Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently find PIDs of many processes started by services

Tags:

bash

centos7

I have a file with many service names, some of them are running, some of them aren't.

foo.service
bar.service
baz.service

I would like to find an efficient way to get the PIDs of the running processes started by the services (for the not running ones a 0, -1 or empty results are valid).

Desired output example:

foo.service:8484
bar.server:
baz.service:9447

(bar.service isn't running).

So far I've managed to do the following: (1)

cat t.txt | xargs -I {} systemctl status {} | grep 'Main PID' \
                                                | awk '{print $3}'

With the following output:

8484
9447

But I can't tell which service every PID belongs to.

(I'm not bound to use xargs, grep or awk.. just looking for the most efficient way).

So far I've managed to do the following: (2)

for f in `cat t.txt`; do
    v=`systemctl status $f | grep 'Main PID:'`;
    echo "$f:`echo $v | awk '{print \$3}'`";
done;

-- this gives me my desired result. Is it efficient enough?

like image 462
bomba6 Avatar asked Aug 10 '16 08:08

bomba6


People also ask

How do I find PID of all processes?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column. Click on any column name to sort.

How do I find the PID of a systemd service?

Use systemctl to get process identifier for specified service. systemd version. Inspect ssh service status.

Can a process have multiple PIDS?

Pids are one-per process. There will NEVER be more than 1 pid for a process - the internal data structures that handle the process in the OS only have a single PID field in them.


1 Answers

I ran into similar problem and fount leaner solution:

systemctl show --property MainPID --value $SERVICE

returns just the PID of the service, so your example can be simplified down to

for f in `cat t.txt`; do
    echo "$f:`systemctl show --property MainPID --value $f`";
done
like image 101
Yorik.sar Avatar answered Nov 07 '22 13:11

Yorik.sar