From af730c79a663bd3cd63f6482f43f9253f349c11d Mon Sep 17 00:00:00 2001 From: Matthew Rosato Date: Wed, 25 Oct 2023 11:15:45 -0400 Subject: [PATCH] libutil/util_lockfile: add routine to return owning pid of file lock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Provide a mechanism via which a caller can query the pid of the process currently holding the file lock. Reviewed-by: Jan Höppner Reviewed-by: Boris Fiuczynski Acked-by: Steffen Eiden Signed-off-by: Matthew Rosato Signed-off-by: Steffen Eiden --- include/lib/util_lockfile.h | 2 ++ libutil/util_lockfile.c | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/include/lib/util_lockfile.h b/include/lib/util_lockfile.h index 15c2f5ab..0945d191 100644 --- a/include/lib/util_lockfile.h +++ b/include/lib/util_lockfile.h @@ -23,4 +23,6 @@ int util_lockfile_parent_lock(char *lockfile, int retries); int util_lockfile_release(char *lockfile); int util_lockfile_parent_release(char *lockfile); +int util_lockfile_peek_owner(char *lockfile, int *pid); + #endif /** LIB_UTIL_LOCKFILE_H @} */ diff --git a/libutil/util_lockfile.c b/libutil/util_lockfile.c index 54404426..2c79531d 100644 --- a/libutil/util_lockfile.c +++ b/libutil/util_lockfile.c @@ -299,3 +299,35 @@ int util_lockfile_parent_release(char *lockfile) { return do_lockfile_release(lockfile, getppid()); } + +/** + * Return the pid that owns the specified lockfile. + * + * @param[in] lockfile Path to the lock file + * @param[in,out] pid Buffer to place owning pid + * + * @retval 0 pid provided in buffer + * @retval !=0 Error, no pid provided + */ +int util_lockfile_peek_owner(char *lockfile, int *pid) +{ + char buf[BUFSIZE]; + int fd, len; + + if (!lockfile || !pid) + return UTIL_LOCKFILE_ERR; + + /* Open lockfile, read the owning pid if it exists */ + fd = open(lockfile, O_RDONLY); + if (fd < 0) + return UTIL_LOCKFILE_ERR; + + len = read(fd, buf, sizeof(buf)); + close(fd); + if (len <= 0) + return UTIL_LOCKFILE_ERR; + buf[len] = 0; + *pid = atoi(buf); + + return 0; +}