[Ocfs2-tools-devel] [PATCH 2/2] o2hbmonitor: add lockfile

Srinivas Eeda srinivas.eeda at oracle.com
Tue Nov 2 12:58:24 PDT 2010


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);
+	}
+}
+
 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();
-- 
1.5.6.5




More information about the Ocfs2-tools-devel mailing list