Xhark
Xhark

Reputation: 841

Reading /proc/pid/smaps

I'm trying to get the value of the lines with the same name in a smap file using bash, but i don't know how to do it. For example I need to get the value of every line starting with "Size:" int order to get the total size. What is the best way to do it?

Example of smap file:

enter image description here

Upvotes: 0

Views: 668

Answers (2)

F4240
F4240

Reputation: 148

I assume size is only gave in kB

#!/usr/env/bin bash
sum=0
grep "^Size:" /proc/pid/smaps | (while read line
do
 size=$(echo "$line" | tr -s '\t' ' ' | cut -d' ' -f2)
 sum=$((sum + size))
done
echo $sum) | xargs -I{} echo "total size: {} kB"

1- Get all size lines

grep "^Size:" /proc/pid/smaps

2- Retrieve the interesting part of the current matching line and perfom stuff on it (in our case sum it)

while read line
do
 size=$(echo "$line" | tr -s '\t' ' ' | cut -d' ' -f2)
 sum=$((sum + size))
done

Then enclose it into parenthesis whith an echo to pull out value of the while statement

| (while read line
do
 size=$(echo "$line" | tr -s '\t' ' ' | cut -d' ' -f2)
 sum=$((sum + size))
done
echo $sum) |

3- Now the total size is available from the pipe and you can use it

 xargs -I{} echo "total size: {} kB"

Upvotes: 1

Finbar Crago
Finbar Crago

Reputation: 444

#!/bin/bash
SUM=0
while read -r line
do
    f=($line)
    if [ "${f[0]}" == "Size:" ]
    then
        size=$(numfmt --from=iec --suffix=B "${f[1]}${f[2]^^}")
        SUM=$(($SUM + ${size: : -1}))
    fi
done < /proc/$$/smaps
echo "I have $(numfmt --to=iec $SUM) in /proc/$$/smaps!"

The above script loops /proc/$$/smaps spliting each line by whitespace then uses numfmt to convert any value of Size to bytes.

Upvotes: 0

Related Questions