[Ocfs2-tools-devel] [PATCH 2/2] o2hbmonitor: add lockfile
Tristan Ye
tristan.ye at oracle.com
Tue Nov 9 21:23:22 PST 2010
Comments inlined;)
Srinivas Eeda wrote:
> This patch creates file /var/run/o2hbmonitor.pid and takes exclusive lock to
> limit multiple processes getting spawned.
>
> Signed-off-by: Srinivas Eeda <srinivas.eeda at oracle.com>
> ---
> o2monitor/o2hbmonitor.c | 45 +++++++++++++++++++++++++++++++++++++++++++++
> 1 files changed, 45 insertions(+), 0 deletions(-)
>
> diff --git a/o2monitor/o2hbmonitor.c b/o2monitor/o2hbmonitor.c
> index f01da76..ff12ceb 100644
> --- a/o2monitor/o2hbmonitor.c
> +++ b/o2monitor/o2hbmonitor.c
> @@ -61,6 +61,8 @@
> #define SLOW_POLL_IN_SECS 10
> #define FAST_POLL_IN_SECS 2
>
> +#define LOCKFILE_NAME "/var/run/o2hbmonitor.pid"
> +
> char *progname;
> int interactive;
> int warn_threshold_percent;
> @@ -300,6 +302,48 @@ static void monitor(void)
> }
> }
>
> +static void lockfile(void)
> +{
> + int fd, error;
> + struct flock lock;
> + char buf[33];
> +
> + memset(buf, 0, 33);
> +
> + fd = open(LOCKFILE_NAME, O_CREAT|O_WRONLY,
> + S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
> + if (fd < 0) {
> + fprintf(stderr, "cannot open/create lock file %s\n",
> + LOCKFILE_NAME);
> + exit(EXIT_FAILURE);
> + }
> +
> + lock.l_type = F_WRLCK;
> + lock.l_whence = SEEK_SET;
> + lock.l_start = 0;
> + lock.l_len = 0;
> +
> + error = fcntl(fd, F_SETLK, &lock);
> + if (error) {
> + fprintf(stderr, "o2hbmonitor is already running\n");
> + exit(EXIT_FAILURE);
> + }
> +
> + error = ftruncate(fd, 0);
> + if (error) {
> + fprintf(stderr, "cannot clear lock file %s\n", LOCKFILE_NAME);
> + exit(EXIT_FAILURE);
> + }
> +
> + sprintf(buf, "%d\n", getpid());
> +
> + error = write(fd, buf, strlen(buf));
> + if (error <= 0) {
> + fprintf(stderr, "cannot write lock file %s\n", LOCKFILE_NAME);
> + exit(EXIT_FAILURE);
> + }
> +}
> +
Hi Srini,
Just curious why not using a in-memory semaphore for the exclusion:
---------------------------------------------------------------
#define O2HB_SEM_MAGIC_KEY 0x4A32594B
int main()
{
...
daemon();
semid = semget(O2HB_SEM_MAGIC_KEY, 1, IPC_CREAT|IPC_EXCL);
if (semid < 0) {
if (errno = EEXIST)
syslog(LOG_INFO "o2hbmonitor is already running.\n");
else
fprintf(stderr, "failed to get semaphore.\n");
exit(semid);
}
openlog();
monitor();
sem_close();
}
---------------------------------------------------------------
Lockfile solution has the possibility to allow duplicated monitors when
user remove lockfile arbitrarily.
> static void usage(void)
> {
> fprintf(stderr, "usage: %s [-w percent] -[ivV]\n", progname);
> @@ -359,6 +403,7 @@ int main(int argc, char **argv)
> strerror(errno));
> }
>
> + lockfile();
> openlog(progname, LOG_CONS|LOG_NDELAY, LOG_DAEMON);
> monitor();
> closelog();
More information about the Ocfs2-tools-devel
mailing list