Fratink
Fratink

Reputation: 124

Memory Requirements of Shell Variable Assignment

I have a very resource limited system, where I have around 900kB of free memory and need to implement a script that reads from a local file, gets an IP address, and then pings it and looks for a response (to check that it is still on a working network).

The problem I have is not in the parsing of files or the passing of parameters, it's that when I attempt to use command substitution to create a variable to ping with, I can see the device freeze and it returns a SIGSEGV error code:

addrVar=`cat some_file_with_only_an_ip_address`

This seems like a trivial task, the parsing of a text file should be much more memory and processor intensive but it works fine. I can't seem to find any hints anywhere that have the same or similar issues. Does anyone have any idea why this doesn't work and possibly a solution?

The complete example code is:

#!/bin/sh
sed -nr 's/IPADDR="([^ ]+)"/\1/p' /etc/config/net > tmpVarFile
var1=`cat tmpVarFile` #this fails, but not the above

Where tmpVarFile contains only an ip address

Thanks!

Solution

Please see @CharlesDuffy's answer below.

The best way to make this work was to read in the /etc/config/net file which was formatted like a set of shell variables (eg. ipaddress="x.x.x.x") then simply use the following:

. /etc/config/net
if ping -c 1 ipaddress;
then
echo "Success"
else
echo "Failure"
fi

Hope that helps!

Upvotes: 0

Views: 61

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295520

There's an easy workaround here, since you only need to read one line:

read -r var1 <tempVarFile

This avoids use of any subprocesses altogether, substantially decreasing memory use (most of which will be associated with the fork() to start a subshell -- which wouldn't be too large on modern platforms doing copy-on-write, but it's hard to tell what ancient, tiny embedded platforms will do -- and the fork() again to run /bin/cat).


Alternately, if /etc/config/net is trusted, and guaranteed to be a valid shell script without unwanted side effects:

. /etc/config/net
if ping "$IPADDR"; then
  : ...etc...
fi

Upvotes: 2

Related Questions