Are there any alternatives to pidof? (smaller footprint)

alternativescpupidofprocess

Well, I've just found out that with extensive usage of pidof in very short intervals, the seemingly tiny tool can be a great CPU hog. (Source: top)
On my older machine, it can easily reach 30 percent peaks especially in batch usage, though only for a short time, but I think that for a simple task like finding the PID of a process, the footprint of such tool should be one fifth of pidof's (if at all).

That is also why I wonder if it might be more sensible to "construct" the finding of the process ID with built-in standard tools. It would not be surprising to me if the sum of CPU load caused by executing the whole pipe managed to stay below the load caused by running pidof standalone.

Furthermore, it would be interesting to know what is causing these high peaks. Maybe there is even somebody here amongst you guys who has dug a little deeper into the pidof code? 🙂

Best Answer

Here are some examples to find pids of processes named "apache2". There are minor differences (newlines in output) between these and pidof but otherwise ought to work the same, in pipelines, etc.

Using pidof:

$ pidof apache2
31751 31750 31749 31748 31747 31489 31488 31487 31486 31485 1500

Newline-separated:

$ ps aux | grep apache2 | grep -v grep | awk -n '{print $2}'
1500 
31485 
31486 
31487 
31488 
31489 
31747 
31748 
31749 
31750 
31751 

Space-separated:

$ ps aux | grep apache2 | grep -v grep | awk -n '{printf $2" "}'
1500 31485 31486 31487 31488 31489 31747 31748 31749 31750 31751 

I did some silly timings of the above commands.

$ date +%T:%N; pidof apache2 ;  date +%T:%N
17:06:05:627088798
31751 31750 31749 31748 31747 31489 31488 31487 31486 31485 1500
17:06:05:634500908

$ date +%T:%N; ps aux | grep apache2 | grep -v grep | awk -n '{printf $2" "}' ;  date +%T:%N
17:06:29:887314682
1500 31485 31486 31487 31488 31489 31747 31748 31749 31750 31751
17:06:29:903997288

pidof: 7,412,110 nanoseconds

ps | grep | awk : 16,682,606 nanoseconds

On my machine, pidof is loads faster (as expected).

The output of pidof seems to be sorted reverse, so this would be my preferred alternative incantation:

$ ps aux | grep apache2 | grep -v grep | awk -n '{print $2}' | sort -rn
31751
31750
31749
31748
31747
31489
31488
31487
31486
31485
1500
Related Question