[Techtalk] probably a stupid scripting question

Kathryn Hogg kjh at flyballdogs.com
Sun Nov 8 08:05:35 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.

exec replaces the current process with the process being exec'ed.  If you
simply run the new process in the background (&) you will have two
processes running.  In your case these two processes would be your script
and the sleep process being exec'ed.

Generally you would use exec in a situation where the calling process has
performed its usefulness and needs to hand over to another process.  The
canonical use of exec is the login command.  Traditionally, login is run
by the system on each terminal that the system has.  It prompts for
username and password and once validated, it execs the user's shell
(bash).  The system (the init process actually), doesn't even realized
this happens.  It's already issued a wait(2) call on the original pid. 
The shell inherits the pid of the login process so init will now be
waiting for bash to exit.  When the user quits the shell process, init
catches this and then invokes a new copy of login.


Exec is always a built-in command in shells.  I'll omit the explanation of
why for you to ponder.


-- 
Kathryn
http://womensfooty.com
National Team Donation - http://womensfooty.com/freedom/donate


More information about the Techtalk mailing list