qemu-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Qemu-devel] [PATCH 1/2] util: Introduce qemu_get_pid_name


From: Michal Privoznik
Subject: [Qemu-devel] [PATCH 1/2] util: Introduce qemu_get_pid_name
Date: Tue, 20 Sep 2016 16:54:52 +0200

This is a small helper that tries to fetch binary name for given
PID.

Signed-off-by: Michal Privoznik <address@hidden>
---
 include/qemu/osdep.h | 10 ++++++++++
 util/oslib-posix.c   | 36 ++++++++++++++++++++++++++++++++++++
 util/oslib-win32.c   |  7 +++++++
 3 files changed, 53 insertions(+)

diff --git a/include/qemu/osdep.h b/include/qemu/osdep.h
index 9e9fa61..384bfe2 100644
--- a/include/qemu/osdep.h
+++ b/include/qemu/osdep.h
@@ -388,6 +388,16 @@ void os_mem_prealloc(int fd, char *area, size_t sz, Error 
**errp);
 int qemu_read_password(char *buf, int buf_size);
 
 /**
+ * qemu_get_pid_name:
+ * @pid: pid of a process
+ *
+ * For given @pid fetch its name. Caller is responsible for
+ * freeing the string when no longer needed.
+ * Returns allocated string on success, NULL on failure.
+ */
+char *qemu_get_pid_name(pid_t pid);
+
+/**
  * qemu_fork:
  *
  * A version of fork that avoids signal handler race
diff --git a/util/oslib-posix.c b/util/oslib-posix.c
index f2d4e9e..9fe5ba9 100644
--- a/util/oslib-posix.c
+++ b/util/oslib-posix.c
@@ -46,6 +46,7 @@
 
 #ifdef __FreeBSD__
 #include <sys/sysctl.h>
+#include <libutil.h>
 #endif
 
 #include "qemu/mmap-alloc.h"
@@ -430,6 +431,41 @@ int qemu_read_password(char *buf, int buf_size)
 }
 
 
+char *qemu_get_pid_name(pid_t pid)
+{
+    char *name = NULL;
+    FILE *f;
+    char pid_path[PATH_MAX];
+    char buf[PATH_MAX];
+    size_t len;
+
+#if defined(__FreeBSD__)
+    /* BSDs don't have /proc, but they provide a nice substitute */
+    struct kinfo_proc *proc = kinfo_getproc(pid);
+    if (proc) {
+        name = g_strdup(proc->ki_comm);
+        free(proc);
+    }
+#else
+    /* Assume a system with reasonable procfs */
+    snprintf(pid_path, sizeof(pid_path), "/proc/%d/cmdline", pid);
+    f = fopen(pid_path, "r");
+    if (!f) {
+        return NULL;
+    }
+
+    len = fread(buf, 1, sizeof(buf), f);
+    if (len) {
+        name = g_strdup(buf);
+    }
+    fclose(f);
+
+#endif
+
+    return name;
+}
+
+
 pid_t qemu_fork(Error **errp)
 {
     sigset_t oldmask, newmask;
diff --git a/util/oslib-win32.c b/util/oslib-win32.c
index 4c1dcf1..128c6b8 100644
--- a/util/oslib-win32.c
+++ b/util/oslib-win32.c
@@ -575,6 +575,13 @@ int qemu_read_password(char *buf, int buf_size)
 }
 
 
+char *qemu_get_pid_name(pid_t pid)
+{
+    /* XXX Implement me */
+    return NULL;
+}
+
+
 pid_t qemu_fork(Error **errp)
 {
     errno = ENOSYS;
-- 
2.8.4




reply via email to

[Prev in Thread] Current Thread [Next in Thread]