In /var/lock/subsys/ directory, there are various files like network, iptables, ip6tables, sshd, rsyslog etc. all these files are the lock files created by their init scripts. Most of these files may be empty.
These files play the important role in Linux startup and shutdown process. When a service is started through an init script, a file is touched in the /var/lock/subsys/ directory with the same name as the init script. This lock file helps in various manners like:
- This file represents that the service should be running or subsystem locked.
- It helps to avoid another instance of a service, if it accidentally started again.
- It is mandatory to create, if service need to be stopped in shutdown.
When the service is stopped, this file is removed.
However only lock file is not enough to know that the service is running or not. Status of a running service can be captured by using status function defined in /etc/rc.d/init.d/functions. Following command in an init script show the status of the service (if status case created in init script):
service <servicename> status
It checks both PID and the lock file of the service. If PID is not found but the lock file exists, you will get following message:
dead but subsys locked
It is not always mandatory to create lock file, the services can be started and stopped without it. But it can create problem during shutdown and RUNLEVEL switch. So follow the recommended steps (recommended by me) to write a good init script (also drafting a tutorial for writing init script):
- In start section of init script touch the lock file after starting the service. You can use touch at the end of start case.
- Don’t forget to check the lock file before starting the service in start case to avoid the multiple session of same service.
if [ ! -f /var/lock/subsys/ ]; then start # start service here fi
- Don’t forget to remove the lock in stop case, it can also be added at the end of stop case.
rm -f /var/lock/subsys/<servicename>
In case system goes power down, lock files remain exist in the system due to non-execution of stop case. It does not tend it to failure as we added a check of existence of lock file in start case. , But the PID of those services will not found that means service is staled. During startup process, init checks if PID of a service exist or not. It realize a stale lock file, and clean itself up, which allow the init script to start the service successfully.