I created a client-server application and now I would like to deploy it.
While development process I started the server on a terminal and when I wanted to stop it I just had to type “Ctrl-C”.
Now want to be able to start it in background and stop it when I want by just typing:
/etc/init.d/my_service {stop|stop}
I know how to do an initscript, but the problem is how to actually stop the process ?
I first thought to retrieve the PID with something like:
ps aux | grep "my_service"
Then I found a better idea, still with the PID: Storing it on a file in order to retrieve it when trying to stop the service.
Definitely too dirty and unsafe, I eventually thought about using sockets to enable the “stop” process to tell the actual process to shut down.
I would like to know how this is usually done ? Or rather what is the best way to do it ?
I checked some of the files in the init.d and some of them use PID files but with a particular command “start-stop-daemon”. I am a bit suspicious about this method which seems unsafe to me.
If you have a utility like start-stop-daemon available, use it.
start-stop-daemonis flexible and can use 4 different methods to find the process ID of the running service. It uses this information (1) to avoid starting a second copy of the same service when starting, and (2) to determine which process ID to kill when stopping the service.--pidfile: Check whether a process has created the file pid-file.--exec: Check for processes that are instances of this executable--name: Check for processes with the name process-name--user: Check for processes owned by the user specified by username or uid.The best one to use in general is probably
--pidfile. The others are mainly intended to be used in case the service does not create a PID file.--exechas the disadvantage that you cannot distinguish between two different services implemented by the same program (i.e. two copies of the same service). This disadvantage would typically apply to--namealso, and, additionally,--namehas a chance of matching an unrelated process that happens to share the same name.--usermight be useful if your service runs under a dedicated user ID which is used by nothing else. So use--pidfileif you can.For extra safety, the options can be combined. For example, you can use
--pidfileand--exectogether. This way, you can identify the process using the PID file, but don’t trust it if the PID found in the PID file belongs to a process that is using the wrong executable (it’s a stale/invalid PID file).I have used the option names provided by
start-stop-daemonto discuss the different possibilities, but you need not usestart-stop-daemon: the discussion applies just as well if you use another utility or do the matching manually.