# Help with rc.d script



## tuaris (Nov 29, 2013)

I'm trying to write a startup and shutdown script but I am stuck on one item.  This particular daemon needs to be shut down by issuing a command via the binary itself.   So I create a custom stop_cmd procedure:

```
mydaemon_stop()
{
    if checkyesno ${rcvar}; then
	echo "Stopping ${name}."
      $command stop
	wait_for_pids ${pidfile}
    fi
}
```

However, if it's not running and a user tries to stop it, it errors out:

```
error: couldn't connect to server
```

I'd like something a little more "clean".  Looking at the www/apache22 rc.d script I see they have some extra stuff:

```
apache22_requirepidfile()
{
    apache22_checkconfig

	if [ ! "0`check_pidfile ${pidfile} ${command}`" -gt 1 ]; then
		echo "${name} not running? (check $pidfile)."
		exit 1
	fi
}
```

Should I do something like that or is there a better way?


----------



## usdmatt (Nov 29, 2013)

From /etc/rc.subr


```
# check_pidfile pidfile procname [interpreter]
#       Parses the first line of pidfile for a PID, and ensures
#       that the process is running and matches procname.
#       Prints the matching PID upon success, nothing otherwise.
#       interpreter is optional; see _find_processes() for details.
#
```

So yes, this does seem like a fairly elegant way of making sure your process is running before trying to stop it. Assuming of course that the start routine is creating the necessary PID file (The rc system may have functionality in place to do this for you).

Seeing as these functions are provided by the FreeBSD rc system, and are used by at least one (fairly important) port, I'd suggest using the same system is probably the best choice.

Edit: Also, what is the checkyesno doing? If you're checking if the program is enabled

```
program_enable="X"
```
then I _think_ the rc system takes care of checking that anyway?


----------

