monit reload - how to know when it is finished?

I have this requirement to add services to monit dynamically. So what I am doing is copying the service monit file to /etc/monit.d/ (which is included in /etc/monitrc) and reloading monit.

cp <service-monit-file> /etc/monit.d/
monit reload
monit monitor <service-name>

Now monit commands run in background. So, monit monitor command fails (service not found) as monit reload did not finish immediately.

So what approach can be taken to ensure that monit monitor is called only after monit reload finishes. I have tried monit -I reload, but the result is same.

Checking monit log with tail and breaking when "reloaded" string comes is also not possible as tail will output to stdout, which is not allowed.


Solution 1:

I can't reproduce this issue (I get a different error) but I guess the monit monitor command fails with a non-zero return value in your case. Then I would do:

while ! monit monitor <service-name> 2>/dev/null
do
    sleep 1
done

Note: you may want to add a timeout mechanism to avoid an infinite while loop.