linuxcommand-linexargs

How to use xargs to get elapsed time for running processes


I want get the run times of some processes. Here is what I am doing

ps -ef | grep "python3 myTask.py" | awk '{print $2}' | xargs -n1 ps -p {} -o etime

I want to get the pids by

ps -ef | grep "python3 myTask.py" | awk '{print $2}'

then pass these along to the

ps -p {} -o etime

by using xargs, but its not working. I get

error: process ID list syntax error

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).
error: process ID list syntax error

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).

what am i doing wrong?


Solution

  • You can use the following command:

    pgrep -f "python3 myTask.py" | xargs -i{} ps -p {} -o etime
    

    pgrep - Look up or signal processes based on name and other attributes.

    -f, --full - The pattern is normally only matched against the process name. When -f is set, the full command line is used.

    For further reading, see man pgrep.


    The missing part from the xargs segment was -i{}, which invokes the command for each argument, whilst {} will be replaced by it.

    -i[replace-str], --replace[=replace-str] - This option is a synonym for -Ireplace-str if replace-str is specified.

    For further reading, see man xargs.