-1

I want to know How to write a shell script that can get CPU usage from a linux server.

I do know how to do it with ps and top on a linux pc. While the problem here is I need to submit my job using a shell script to a linux server.

I tried

myjob
ps ux U myname

It runs in sequence. So, I don't know the CPU usage of myjob.

myjob &
ps ux U myname

The & sign just suspend myjob. Again, the whole purpose here is to know the CPU usage of myjob.

Please let me know how to run the two line in parallel or there is some other way around.

Thank you in advance.

7
  • The & sign sends the process to the background.
    – Blender
    Dec 29, 2012 at 8:08
  • Thank you for trying to help. @sarathi I don't know how to let ps get the info when myjob is running.
    – Yao Zhao
    Dec 29, 2012 at 8:13
  • @Blender, yes. when using "&" myjob is not running and shows 0.0% CPU usage.
    – Yao Zhao
    Dec 29, 2012 at 8:14
  • Does your program ask for input from stdin?
    – Barmar
    Dec 29, 2012 at 8:44

4 Answers 4

2

Why not just use the time command:

time myjob
0

Actually, calling myjob using the "&" at the end simply creates another process with your job. myjob would still run in the background and it would allow you to get the process' CPU usage using top. For example, I created test.cpp I ran

./test&

which returned

[1] 7178

where 7178 is the process' pid then

top -pid 7178

gives the process' CPU consumption in realtime.

9
  • The test.cpp had while(1){int a = 3; a = 2;} looping continually and using 100% of my CPU.
    – Sam
    Dec 29, 2012 at 8:16
  • Also, if you do ps just after myjob was started, it is very plausible that your job did not have time to start it's main CPU usage, so that it may appear as if it used 0%. Try running ps a few seconds after myjob has started.
    – Sam
    Dec 29, 2012 at 8:20
  • Don't call your binaries test it is a shell (bash) builtin. Call them eg testprog Dec 29, 2012 at 8:23
  • @BasileStarynkevitch my bad, I forgot the "./" that I used when testing. I changed my answer
    – Sam
    Dec 29, 2012 at 8:26
  • @Sam Thank you to bring the main CPU usage problem, is sleep the right command for that. By the way I will vote +1 when I get 15 reputation. :)
    – Yao Zhao
    Dec 29, 2012 at 8:39
0
myjob &
process_id=$!
...now use the process_id in your ps command
0

Have you tried iostat command?

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.