help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] The real usage of exec


From: Greg Wooledge
Subject: Re: [Help-bash] The real usage of exec
Date: Mon, 20 Apr 2015 08:35:40 -0400
User-agent: Mutt/1.4.2.3i

On Sun, Apr 19, 2015 at 09:22:18PM -0500, Peng Yu wrote:
> Hi, I am wondering what is the real usage of exec.

exec does two completely different things:

 1) It acts as "open" and "close" for file descriptors within a script.

 2) It causes the script (and the shell reading it) to replace itself
    with another program.

Here's an example of 1):

#!/bin/bash
exec 3<>/dev/tcp/www.google.com/80 || exit
printf 'HEAD / HTTP/1.1\nHost: www.google.com\nConnection: close\n\n' >&3
cat <&3
exec 3>&-

The first exec opens FD 3 as a read/write socket.  The second exec closes
it.

Here's an example of 2):

#!/bin/sh
exec gzip -d ${1+"$@"}

This is a possible implementation of "gunzip", written as a wrapper around
gzip.  It's considered good form for a wrapper script to exec the thing
it's wrapping, for two reasons: (a) it gets rid of the shell process
which is no longer needed, freeing up resources; and (b) it preserves
the PID of the script, and its relationship to its parent process.

For this reason, "run scripts" used with DJB's daemontools are also
written this way.  Here's a real one:

$ cat /service/greybot/run 
#!/bin/sh
cd /home/greybot || exit 1
exec /usr/local/bin/setuidgid greybot ./greybot.pl 2>&1

The wrapper simply changes directory and drops privileges (from root
to greybot), and runs the actual greybot.pl program.  The daemontools
supervisor then has control over the greybot.pl program, which is now
its direct child.

For more details, see http://mywiki.wooledge.org/WrapperScript .

This style of boot system is becoming much more popular nowadays, as
the world (or at least the Linux part of it) is moving away from the
legacy BSD init and System V init days, where daemons were launched
into orbit without a leash.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]