――I decided to write this article this time because I wrote a summary about cron in the previous Summary and common errors about cron. Continuing from the last time, I will write about process monitoring using cron.
――It will be an article for beginners as before.
――I won't write about cron in detail, so if you don't know much about cron, it may be easier to understand if you read the previous article or check it out.
--Process monitoring
--Display the target process list with pgrep, and check how many scripts you are monitoring are running from the list. --Branch the result with an if statement and perform the necessary processing in the branch.
vi
crontab -e
*/5 * * * * /bin/sh shell.sh
ShellScript
#! /bin/bash
PROCESS_NAME=nginx
count=`pgrep $PROCESS_NAME | wc -l`
if [ $count = 0 ]; then
echo "$PROCESS_NAME is stop"
systemctl start nginx
echo "$PROCESS_NAME is Start"
else
echo "$PROCESS_NAME is running"
fi
vi
crontab -e
*/5 * * * * /bin/sh shell.sh
//If you write the above in crontab, the set shell will be executed every 5 minutes.
*/5 * * * * /bin/sh shell.sh >> /Any place/log.txt 2>&1
//If you want to keep the contents executed as a file, you can write it like this.
//2>&1 is a mixture of standard output and error output.
ShellScript
#! /bin/bash
//This is like a cliché in writing a shell.
PROCESS_NAME=nginx
//Here you define the process you want to monitor. This time it's nginx.
count=`pgrep $PROCESS_NAME | wc -l`
//I want to count the running processes, so I count the number of processes and assign them to a variable.
//Get a list of process IDs that match the pattern with pgrep.
// |(pipeline)With wc-Connect l to get the number of lines in the process.
* As an aside, wc can display the number of words and bytes in addition to the number of lines because the word count is the origin of the name.
if [ $count = 0 ]; then
echo "$PROCESS_NAME is stop"
systemctl start nginx
echo "$PROCESS_NAME is Start"
else
echo "$PROCESS_NAME is running"
fi
//If the number of processes defined earlier in this if statement is 0, it means that nginx is stopped, so write the shell to start as above.
//If not, the nginx process has started normally and echo to it."$PROCESS_NAME is running"Is returned.
――It's easy to combine this cron setting with the shell script explained, but you can run the shell every 5 minutes to check the process, and if the process is stopped, it will start automatically.
――You can deepen your understanding of shell scripts by reading the articles below.
Introduction of basic commands for shell scripts for beginners [UNIX & Linux Command Shell Script Reference] (https://shellscript.sunone.me/tutorial.html)
This time, I wrote an article about process monitoring using cron, which is a continuation of the article I wrote last time. If you have any mistakes, please let me know in the comments, etc., as it will be my study. Next time, I'd like to write an article about Vagrant and middleware settings.
Recommended Posts