diff --git a/src/libvirt_private.syms b/src/libvirt_private.syms index 9d5c814181..e7e8df526c 100644 --- a/src/libvirt_private.syms +++ b/src/libvirt_private.syms @@ -1816,6 +1816,7 @@ virPidFileBuildPath; virPidFileConstructPath; virPidFileDelete; virPidFileDeletePath; +virPidFileForceCleanupPath; virPidFileRead; virPidFileReadIfAlive; virPidFileReadPath; diff --git a/src/util/virpidfile.c b/src/util/virpidfile.c index a3b8846aae..098458f7eb 100644 --- a/src/util/virpidfile.c +++ b/src/util/virpidfile.c @@ -37,6 +37,7 @@ #include "c-ctype.h" #include "areadlink.h" #include "virstring.h" +#include "virprocess.h" #define VIR_FROM_THIS VIR_FROM_NONE @@ -567,3 +568,44 @@ virPidFileConstructPath(bool privileged, VIR_FREE(rundir); return ret; } + + +/** + * virPidFileForceCleanupPath: + * + * Check if the pidfile is left around and clean it up whatever it + * takes. This doesn't raise an error. This function must not be + * called multiple times with the same path, be it in threads or + * processes. This function does not raise any errors. + * + * Returns 0 if the pidfile was successfully cleaned up, -1 otherwise. + */ +int +virPidFileForceCleanupPath(const char *path) +{ + pid_t pid = 0; + int fd = -1; + + if (!virFileExists(path)) + return 0; + + if (virPidFileReadPath(path, &pid) < 0) + return -1; + + if (virPidFileAcquirePath(path, false, 0) == 0) { + virPidFileReleasePath(path, fd); + } else { + virResetLastError(); + + /* Only kill the process if the pid is valid one. 0 means + * there is somebody else doing the same pidfile cleanup + * machinery. */ + if (pid) + virProcessKillPainfully(pid, true); + + if (virPidFileDeletePath(path) < 0) + return -1; + } + + return 0; +} diff --git a/src/util/virpidfile.h b/src/util/virpidfile.h index ca1dbff2e3..eb6516ca15 100644 --- a/src/util/virpidfile.h +++ b/src/util/virpidfile.h @@ -74,4 +74,6 @@ int virPidFileConstructPath(bool privileged, const char *progname, char **pidfile); +int virPidFileForceCleanupPath(const char *path) ATTRIBUTE_NONNULL(1); + #endif /* __VIR_PIDFILE_H__ */