开发者

Linux / Bash using PS -f for specific PID returns in different format than PS -f, also queston about using Grep to parse this

I have a need, for a python script I'm creating, to first get just the PID of a process (based on its name) and then to get from that process, usings its PID, its time duration, which, from the printout below, would be "00:00:00"

root      5686     1  0 Sep23 ?        00:00:00 process-name

I am using this to get just the PID, by the process's name:

ps -ef |grep `whoami`| grep process-name | cut -c10-15

So, this works fine and I am assuming that the cut parameters (-c10-15) would work universally as the placement of the PID shouldn't change (I just got this from a snippet I found)

However, when I try to do something similar to get just the TIME value, such as this it returns it differently

ps -f 5686

returns:

root      5686     1  0 Sep23 ?        S      0:00 /path/to/process

So when I try a cut, as below, I don't think it would work properly as I'm not sure the spacing on this return is consistent and also its showing the time value differently than before (not the original "00:00:00" style of printout.

ps -f 5686 | cut -c40-47

I'm using this in my python script to record the PID of a specific proces开发者_运维知识库s type (by name) so that I can later shut down that instance of the progra when needed. Any advice on what I can do to correct my approach is appreciated


Use the -o option to control what data is output and in what order.

e.g.

$ ps -o pid,time,comm
  PID     TIME COMMAND
 3029 00:00:01 zsh
22046 00:00:00 ps

or

$ ps -o pid,time,comm --no-headers
 3029 00:00:01 zsh
22046 00:00:00 ps

This will make it easier to parse. I would suggest parsing the output with python using (pid, time, cmd) = result.split(2)

Alternatively use the pgrep command to only list processes that match given criteria.


What about using

ps ux | awk '/$PROCESS_NAME/ && !/awk/ {print $2, $10}'

It should give you PID and TIME (adapted from here)

EDIT:
Version with -ef

ps -ef | awk '/$PROCESS_NAME/ && !/awk/ {print $2, $7}'


If you want consistent representation of the CPU time, read /proc/<pid>/stat and read the utime and stime fields.

Read man 5 proc to get the full layout of that file, but the easy bit is that you need the 14th and 15th values, and they're represented in "jiffies" (typically 100 per second), e.g.

% ps -e 2398
2398 ?        00:04:29 ypbind

00:04:29 is 269 seconds

% awk '{ print ($14 + $15) / 100 }' < /proc/2398/stat
269.26

or, in a Bash script without spawning a sub-process:

#!/bin/sh
read -a procstat /proc/pid/stat
let cpu=(procstat[13] + procstat[14]) / 100
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜