[Techtalk] probably a stupid scripting question

Phil Savoie psavoie1783 at rogers.com
Sun Nov 8 08:27:34 UTC 2009


Miriam English wrote:
> Hi folks,
> 
> I was altering a script and wondered what exec did.
> The description I read in the documentation I looked up:
> "Execute command in place of the current process (instead of creating a
> new process)."
> doesn't make a lot of sense to me so I did what I usually do when faced
> with something I don't understand -- I experimented. I created a very
> simple script to see what it did.
> 
> echo "blah1"
> sleep 5
> echo "blah2"
> exec sleep 5
> echo "blah3"
> 
> I kinda thought it would have a delay between printing "blah1" and
> "blah2", but no delay between "blah2" and "blah3", but it doesn't. It
> delays both times, but doesn't print "blah3".
> 
> So now, confounded, I do the other thing I do when faced with something
> I don't understand: find someone who might explain it to me. :)
> 
> Can anybody give me a simple explanation of what exec does? Am I right
> that the exec'ed command takes over current process and if that process
> is (was) a script, then the script is no longer executing?
> If so, what use is that? I notice a lot of application icon scripts use
> exec. Why not use "&" at the end of a command instead? That way the
> script could do other things and end leaving the command to continue on
> its merry way.
> 
> Thanks,
> 
>     - Miriam
> 
Hi Miriam,

The exec does exactly what your def says.  Typically when you run a
command the shell opens a new child to run the process , report the exit
status to the parent then dies.  What exec does is overlay the current
process and run the command without starting a child shell.

To test:

open a terminal and run the ps command without options and note the pid
of your current shell.  Then type csh or another shell.  Run ps again
and note that the second shell is a child of the parent.

Exit the the new shell and run ps to verify only one shell is running
which should be the one that started when you started the terminal session.

Next instead of starting a new shell with the executive of the new
shell, run:

exec csh

Then do ps and note there is only one pid showing.  That of the new c
shell.  This is what the exec does.

Hope I made sense, and you understand

Phil


More information about the Techtalk mailing list