help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] When to use exec to replace the shell?


From: Greg Wooledge
Subject: Re: [Help-bash] When to use exec to replace the shell?
Date: Thu, 28 Jan 2016 08:38:39 -0500
User-agent: Mutt/1.4.2.3i

On Wed, Jan 27, 2016 at 10:22:18PM -0600, Peng Yu wrote:
> According to this, it seems that this usage of exec is not very useful
> nowadays unless one is on a computer with limited resources. Is it so?

If you want a real-life example of when exec is not only the Right Thing,
but also the Only Correct Thing, let's look at a daemontools run script.

Daemontools (http://cr.yp.to/daemontools.html) is a software package
that manages long-running processes (services).  If you're familiar
with systemd, you can think of it as systemd's no-frills predecessor.

When you set up a service for daemontools to manage, you have to
create a program named "run" in a certain directory.  This program
can be written in any language, but shell script is traditional.
It should execute your service, in the foreground, with no funky monkey
business.  The daemontools service manager is the parent of your "run"
program/service, so it knows immediately when you exit, and it can launch
another instance of you automatically (unless you tell it not to).

In order for all of this to work, that parent/child relationship is
essential.  If you write a shell script named "run" that simply executes
"/sbin/yourdaemon", then the service manager is the *grandparent* of
your daemon, instead of the parent.  That means it can't monitor you.
It has no idea whether you're still running.

So, instead of simply executing yourdaemon, a run script must use exec.
Here's an actual example:

$ cat /service/ebase/run
#!/bin/sh
TCLLIBPATH=/opt/ebase5/lib
HOME=/home/ebase
export TCLLIBPATH HOME
cd "$HOME" || exit
exec setuidgid ebase /opt/ebase5/bin/ebased -foreground 2>&1

This same principle applies to runit, systemd unit files, etc.  Of course,
systemd is a bloated mutant godzilla version of daemontools, and doesn't
use shell scripts, instead preferring its own custom configuration
syntax that you have to learn from ground zero... but the concept is
still the same.



reply via email to

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