Processes can be temperamental at times. They can crash for unknown reasons and when someone besides yourself has written them and you don’t have the code or perhaps the time to figure why they have crashed, you can be left in a difficult position particularly if the malfunctioning process is something that your application requires as a necessity. This is exactly the situation that I found myself in over the last few weeks ever since I’ve moved over to using the Jena RDF triplestore engine and its Fuseki SPARQL interface. My whole application at linkedarc.net (to go live any day this week) is built upon the premise that Fuseki is up and running so that I can send it SPARQL queries and get back data that I then display in various forms to the user. The problem is that Fuseki for whatever reason often appears to stop. The solution (if a rather crude and brute force one) is to use scheduled tasks as delivered by cron.
Here’s how you do it:
- Write a shell script along the following lines.
#!/bin/bash #make sure a process is always running. process=PROCESS_NAME makerun=" PROCESS AND PARAMS" if ps ax | grep -v grep | grep $process > /dev/null then echo Process is not running exit else echo restarting process cd PROCESS_PATH $makerun & fi exit
- Save it with a .sh file extension to the location of the target process. Basically, this script looks for the process using the ps command and if it is not found it changes the directory to the process’s directory (this is important for when we schedule it with cron) and then runs the process with any parameters required. To get it working just swap in your own process details in the placeholders and make sure that you amend its privileges to allow any user to execute it.
- Now you need to add the shell script to cron’s schedule. Enter the following command and choose your preferred text editor to make the changes to the schedule file.
- Add a new line to the end of the file replacing SHELL_SCRIPT_PATH with your scripts’ path including its .sh extension. Read the guidelines at the top of the cron file to figure out how to structure the entry. The following entry will run the shell script every one minute.
*/1 * * * * SHELL_SCRIPT_PATH
- Check to see if cron is running the tasks that you expect it be running in the schedule that you have specified by viewing its log file.
grep CRON /var/log/syslog
- If it is running your script following the correct schedule but your process is not up and running you can have the output of the shell script displayed in Ubuntu’s GUI as a popup message by changing the cron task line to read:
*/1 * * * * DISPLAY=:0 notify-send "$(SHELL_SCRIPT_PATH)"
And that’s it. You now should have a background monitor script running every minute to ensure that your flaky process is always up and running.