Question

I'm trying to have a lightweight memory profiler for the matlab jobs that are run on my machine. There is either one or zero matlab job instance, but its process id changes frequently (since it is actually called by another script).

So here is the bash script that I put together to log memory usage:

#!/bin/bash
pid=`ps aux | grep '[M]ATLAB' | awk '{print $2}'`
if [[ -n $pid ]]
then
    \grep VmSize /proc/$pid/status
else
    echo "no pid"
fi

when I run this script in bash like this:

./script.sh

it works fine, giving me the following result:

VmSize:  1289004 kB

which is exactly what I want.

Now, I want to run this periodically. So I run it with watch, like this:

watch ./script.sh

But in this case I only receive:

no pid

Please note that I know the matlab job is still running, because I can see it with the same pid on top, and besides, I know each matlab job take several hours to finish.

I'm pretty sure that something is wrong with the quotes I have when setting pid. I just can't figure out how to fix it. Anyone knows what I'm doing wrong?

PS. In the man page of watch, it says that commands are executed by sh -c. I did run my script like sh -c ./script and it works just fine, but watch doesn't.

Was it helpful?

Solution 2

This

pid=`ps aux | grep '[M]ATLAB' | awk '{print $2}'`

could be changed to:

pid=$(pidof MATLAB)

OTHER TIPS

Why don't you use a loop with sleep command instead?

For example:

 #!/bin/bash
pid=`ps aux | grep '[M]ATLAB' | awk '{print $2}'`

while [ "1" ]
do
if [[ -n $pid ]]
then
    \grep VmSize /proc/$pid/status
else
    echo "no pid"
fi
sleep 10
done

Here the script sleeps(waits) for 10 seconds. You can set the interval you need changing the sleep command. For example to make the script sleep for an hour use sleep 1h.

To exit the script press Ctrl - C

I have no idea why it's not working in watch but you could use a cron job and make the script log to a file like so:

#!/bin/bash
pid=$(pidof MATLAB) # Just to follow previously given advice :)
if [[ -n $pid ]]
then
    echo "$(date): $(\grep VmSize /proc/$pid/status)" >> logfile
else
    echo "$(date): no pid" >> logfile
fi

You'd of course have to create logfile with touch.

You might try just running ps command in watch. I have had issues in the past with watch chopping lines and such when they get too long.

It can be fixed by making the terminal you are running the command from wider or changing the column like this (may need to adjust the 160 to your liking): export COLUMNS=160;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top