[prog] Returning a string from a function, in bash

Almut Behrens almut-behrens at gmx.net
Sat Apr 17 19:34:55 EST 2004


On Fri, Apr 16, 2004 at 08:11:09PM +0200, Riccarda Cassini wrote:
> 
> I was told that running an external program (as a new process) involves
> two system calls (fork/exec), which are rather expensive, compared to
> simply calling a function within the same process. This kind of led me
> to avoid backticks whenever possible. (Mind you, I don't really know
> what I'm talking about, so don't nail me down on that ;-)
>
> In the meantime, I read somewhere in the bash manpage, that using
> backticks to call *functions*, does not actually involve creating a
> new process. Well, when thinking about it, it somehow makes sense...
> (what should be run in that new process - the script itself again?)
> However, I'm not entirely sure I understood this correctly.

actually, if you make a call to a function with "var=`myfunc ...`" a
fork() is done, but in this particular case, it isn't too expensive.
The fork() just duplicates the shell process, so the same mechanics
for capturing stdout can be used, as if you were running an external
program. However, as there is no external program in this case, the
exec() - which would normally replace the current process with the new
program - is not required.

Also, modern operating systems like Linux are rather clever about only
allocating new memory for, and copying memory regions, if they are
being modified in the forked process. Memory regions which are only
read but not written to (like the code segment) can thus be shared.
So, if the called function doesn't modify much program-internal data,
then there's hardly any overhead.

You can always empirically find out what a certain program is doing
(systemcall-wise) using 'strace'. If you run your script like this

strace -f -o trace.out ./script.sh

you can then examine trace.out to see which system calls were made,
and with which parameters etc.  Look for fork() and execve() in this
particular case. The -f tells strace to log system calls for forked
processes, too.


> (...)
>   GPPID=ppidof(ppidof($$))
> 
> which, as we all know in the meantime, doesn't work that way ... ...
> 
> Well, now you at least have an idea what a wannabe hacker does when she 
> has nothing else to do in the evening :-)

Nicely done hacking, Riccarda, I'm impressed. If you carry on like
this, you'll soon have left behind your wannabe status :)

Hugs,
Almut



More information about the Programming mailing list