55

How to get all process ids (pid) (similar to: $ ps aux) but without using ps.

One example of when this would be used is when developing a dotnet 5 application to run on a docker host. The dotnet runtime image is a very cut-down Linux image, with bash, but without ps. When diagnosing an issue with the application, it's sometimes useful to see what processes are running and if separate processes have been spawned correctly. ps is unavailable on this image. Is there an alternative?

GregHNZ
  • 7,946
  • 1
  • 28
  • 30
WB Lee
  • 641
  • 1
  • 6
  • 10

4 Answers4

42

On Linux, all running process have "metadata" stored in the /proc filesystem.

All running process ids:

shopt -s extglob # assuming bash
(cd /proc && echo +([0-9]))
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • 2
    what is the meaning of echo +([0-9]) .Thanks! – WB Lee Oct 02 '15 at 18:59
  • When I open the filessystems, there are some other information but how the +([0-9]) get the pid. Thanks! Sincerely! – WB Lee Oct 02 '15 at 19:07
  • 1
    That's a bash [extended filename globbing pattern]() that matches one or more digits. In the /proc directory, there is a subdirectory for each process (named with the numeric pid), and a bunch of other things – glenn jackman Oct 02 '15 at 20:09
  • 13
    Why was this question closed as unclear? The question seems abundantly clear as evidenced by the on-point answer. Can we get this question reopened? – Seth Difley Dec 11 '18 at 13:44
  • It was most likely closed because there is no effort made by the OP. Note the close message: "Please clarify your specific problem or add additional details to highlight exactly what you need" – glenn jackman Dec 11 '18 at 18:06
  • 14
    Try `for exe in /proc/*/exe; do ls -l $exe; done` – FelixJongleur42 Oct 22 '20 at 09:42
  • Want tp clarify that shopt is not included on the current default dotnet docker image – b-rad15 Sep 22 '21 at 03:29
  • 2
    To also show the command line that started the process, after executing `shopt -s extglob` on its own line, try: `for exe in /proc/+([0-9])/exe; do ls -l $exe; echo "Command line with args:"; tr '\0' '\n' < $(dirname $exe)/cmdline; echo -e '\n'; done` – dlauzon Apr 29 '22 at 15:44
37

Further to the comment by @FelixJongleur42, the command

ls -l /proc/*/exe

yields a parseable output with additional info such as the process user, start time and command.

spume
  • 1,704
  • 1
  • 14
  • 19
18

This one-liner will give you the pid and the cmd with args:

for prc in /proc/*/cmdline; { (printf "$prc "; cat -A "$prc") | sed 's/\^@/ /g;s|/proc/||;s|/cmdline||'; echo; }
Ivan
  • 6,188
  • 1
  • 16
  • 23
1

Based on Ivan's example with some filtering:

for prc in /proc/*/cmdline; { 
    (printf "$prc "; cat -A "$prc") | sed 's/\^@/ /g;s|/proc/||;s|/cmdline||' | grep java ; echo -n; 
}
dmatej
  • 1,518
  • 15
  • 24