Monit is a free open source utility for managing and monitoring, processes, files, directories and filesystems on a UNIX system.

We use monit for monitoring daemon processes to ensure a 24x7 running environment. Monit check the pid number in a pid file belongs to a running process. If a program crashes and dies in a "normal" manner, then the process ID (pid) will not exist and monit will know that the program is not running and restart it even if a pid file exist.

Monit scripts require instructions for starting and stopping a process. An example of monitoring example.rb process is given below:

check process ex with pidfile /Users/akash/pid-example
start program = "/usr/bin/ruby -C/Users/akash/ /Users/akash/example.rb"
as uid 1100 and gid 1100
stop program = "/bin/kill `cat /Users/akash/pid-example`"
as uid 1100 and gid 1100

In the above example, 1100 is the user_id which will run the process. ‘pid-example’ is a file, which contain pid for example.rb process. Monit continuously monitor process with pid written in pid-example and if it isn’t running, monit start the process using the instructions given in start command.

Usually it is difficult to run process that use an environmental variable using monit. The reason for the same is that the shell environment is different from the monit shell environment. So even if you set the environmental variable in shell, running that particular program though monit will not work.

If example.rb would expect en environmental variable RUN_ENV to be set for it’s execution, setting that in shell isn’t sufficient. We should set RUN_ENV in start instructions given to monit:
check process ex with pidfile /Users/akash/pid-example
start program = "/usr/bin/env RUN_ENV=production /usr/bin/ruby -C/Users/akash/ /Users/akash/example.rb"
as uid 1100 and gid 1100
stop program = "/bin/kill `cat /Users/akash/pid-example`"
as uid 1100 and gid 1100

On reading monit FAQs, one can find this answer here. Here it says:
For security reasons monit purges the environment and only sets a spartan PATH variable that contains /bin, /usr/bin, /sbin and /usr/sbin. If your program or script dies, the reason could be that it expects certain environment variables or to find certain programs via PATH. If this is the case you should set the environment variables you need directly in the start or stop script called by monit.

Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.