How to create custom startup scripts
From Wiki-UX.info
Contents
Template "/sbin/rc3.d/S999custom1"
#!/sbin/sh # # Template for custom rc script PATH=/usr/sbin:/usr/bin:/sbin export PATH case $1 in 'start_msg') echo "Starting the <script>" ;; 'stop_msg') echo "Stopping the <script>" ;; 'start') # All required instruction to start the process. Can be a call to another script. rval=1 ;; 'stop') # All required instruction to stop the process. Can be a call to another script. rval=1 ;; *) echo "usage: $0 {start|stop|start_msg|stop_msg}" rval=1 ;; esac exit $rval
Example using a pseudo daemon process
The following example demonstrates a basic startup script using a Posix Shell while loop. The script uses the su command to start the script under bin user profile. Note that to properly stop the process, the process ID of the su child process is used. This is due to the nested nature of calling a shell under a shell approach and not needed when calling binary executables or scripts that don't need to change the user.
1. Create "pseudo.sh" daemon.
# cat > /tmp/pseudo.sh << EOF #!/bin/sh # Pseudo daemon while true do echo $(date) >> /tmp/test.txt sleep 60 done EOF
<pre">
- chown bin:bin /tmp/pseudo.sh
- chmod 0744 /tmp/pseudo.sh
</pre>
2. Test that pseudo daemon works from the command line.
# su bin -c '/tmp/pseudo.sh' & [1] 16158 # ps -ef | grep [p]seudo.sh | awk '{print $2}' | sort -nr | head -n 1 > /tmp/pseudo.pid # ps -ef | grep [p]seudo.sh bin 16160 16158 0 11:55:24 pts/tg 0:00 /bin/sh /tmp/pseudo.sh bin 16158 15944 0 11:55:24 pts/tg 0:00 sh -c /tmp/pseudo.sh # cat /tmp/pseudo.pid # kill -9 $(cat /tmp/pseudo.pid) # sh: 16160 Killed # ps -ef | grep [p]seudo.sh
3. Implement the previous login using the RC startup script.
# cat /sbin/init.d/pseudo #!/sbin/sh # # Pseudo daemon Startup Script PATH=/usr/sbin:/usr/bin:/sbin export PATH case $1 in 'start_msg') echo "Starting the pseudo daemon process" ;; 'stop_msg') echo "Stopping the pseudo daemon process" ;; 'start') # All required instruction to start the process. Can be a call to another script. username="bin" su ${username} -c '/tmp/pseudo.sh' & sleep 1 ps -ef | grep [p]seudo.sh | awk '{print $2}' | sort -nr | head -n 1 > /tmp/pseudo.pid rval=1 ;; 'stop') # All required instruction to stop the process. Can be a call to another script. if [[ -f /tmp/pseudo.pid ]]; then kill -9 $(cat /tmp/pseudo.pid) if [[ $? -eq 0 ]]; then rval=1 else rval=0 fi fi rval=1 ;; *) echo "usage: $0 {start|stop|start_msg|stop_msg}" rval=1 ;; esac exit $rval
# chown bin:bin /sbin/init.d/pseudo # chmod 0755 /sbin/init.d/pseudo
4. Test the start and stop routines
# /sbin/init.d/pseudo usage: /sbin/init.d/pseudo {start|stop|start_msg|stop_msg} # /sbin/init.d/pseudo start # ps -ef | grep [p]seudo bin 16332 16325 0 12:09:33 pts/tg 0:00 /bin/sh /tmp/pseudo.sh bin 16325 1 0 12:09:33 pts/tg 0:00 sh -c /tmp/pseudo.sh # /sbin/init.d/pseudo stop # ps -ef | grep [p]seudo