# Practical rc scripting very short tutorial



## Alain De Vos (Oct 19, 2022)

First make make daemon which will print "Hello World" each few seconds on the screen.
A file /usr/local/etc/myservice2 , chmod 755 with following content:

```
#!/usr/local/bin/mksh
echo "Starting"
while true do
    echo "Hello World"
    sleep 6
done
```
Then we create the rc-script to stop and start this service:
A file /usr/local/etc/myservice, chmod 755 with following content:


```
#!/bin/sh 

# PROVIDE: myservice
# REQUIRE:
# KEYWORD:

. /etc/rc.subr 

name="myservice"
rcvar=myservice_enable
start_cmd="${name}_start" 
stop_cmd="${name}_stop" 
pidfile="/var/run/${name}.pid"
command="/usr/local/etc/rc.d/myservice2"

load_rc_config $name
: ${myservice_enable:=NO}


myservice_start() 
{
if [ -f $pidfile ]
then
    echo "ALREADY STARTED"
else
    /usr/sbin/daemon -p $pidfile ${command}
    echo "Myservice started."
fi
}

myservice_stop() 
{
if [ -f $pidfile ]
then    
    kill -9 `cat $pidfile` 
    echo "My service stopped"
else
    echo "NOT YET STARTED"
fi
}

run_rc_command "$1"
```

Done.

To start&stop the service:

```
service myservice onestart
service myservice onestop
```

You can edit /etc/rc.conf to start it automatic

```
my_service_enable="YES"
```


----------

