1

I have written a command to retrieve a process having maximum CPU% using ps and sort in combination. This command retrieves the first result of the list, and to be more specific I just want the pid of that topmost process. What modifications do I need to do in the command so that it would return the pid of that topmost result and how to store it?

$ ps aux --sort -%cpu | tail -n +2 | head -1
sharwari 2831 14.9 25.9 1725720 976104 ? Sl 21:25 20:03 /usr/lib/firefox/firefox
Etan Reisner
  • 68,917
  • 7
  • 78
  • 118
Mickstjohn09
  • 103
  • 2
  • 10

2 Answers2

1
ps aux --sort -%cpu | tail -n +2 | head -1 | awk '{ print $2 }' > outputfile.txt

This will execute your command, and grab the second column ofinformation with the awk command. Then output is redirected to output.txt (or whichever file you like to save the result in)

Matt
  • 4,580
  • 2
  • 23
  • 36
1

You can just use pipe your ps command to an awk:

ps aux --sort -%cpu | awk 'NR==2{print $2}'
anubhava
  • 664,788
  • 59
  • 469
  • 547
  • If I want to execute this command through a C program, how can I retrieve the value of NR in the C code? – Mickstjohn09 Jan 28 '15 at 06:17
  • `NR` is `awk` variable. If you want output of this command just execute the whole command using `system` function call and grab the output. – anubhava Jan 28 '15 at 06:20
  • If I use exec function to execute the command instead of system function call, how can I get the same job done? – Mickstjohn09 Jan 28 '15 at 06:53
  • Write way to grab the output of an external command is by using `popen`. [See this answer on how to use it](http://stackoverflow.com/a/646254/548225) – anubhava Jan 28 '15 at 07:08