[Spice-devel] [PATCH 1/2 v3] Attempt to manage redirection in a way similar to Unix

Frediano Ziglio fziglio at redhat.com
Fri Apr 29 14:09:47 UTC 2016


This patch allows remote-viewer to redirect output/error streams to
files.
Also if launched from a console program (for instance from the command
prompt) you are able to see output from the console where you launch
the program.
This allow to launch the program with a syntax like
  > remote-viewer.exe --debug > log.txt 2>&1
or simply
  > remote-viewer.exe --debug

Signed-off-by: Frediano Ziglio <fziglio at redhat.com>
---
 src/virt-viewer-util.c | 36 +++++++++++++++++++++++++++++-------
 1 file changed, 29 insertions(+), 7 deletions(-)

Changes from previous version:
- fixed different redirection combinations;
- tested on Windows XP, 7 and 10.

diff --git a/src/virt-viewer-util.c b/src/virt-viewer-util.c
index 8cf52ec..ebe039c 100644
--- a/src/virt-viewer-util.c
+++ b/src/virt-viewer-util.c
@@ -253,6 +253,17 @@ static void log_handler(const gchar *log_domain,
     g_log_default_handler(log_domain, log_level, message, unused_data);
 }
 
+#ifdef G_OS_WIN32
+static BOOL is_handle_valid(HANDLE h)
+{
+    if (h == INVALID_HANDLE_VALUE || h == NULL)
+        return FALSE;
+
+    DWORD flags;
+    return GetHandleInformation(h, &flags);
+}
+#endif
+
 void virt_viewer_util_init(const char *appname)
 {
 #ifdef G_OS_WIN32
@@ -265,13 +276,24 @@ void virt_viewer_util_init(const char *appname)
      */
     CreateMutexA(0, 0, "VirtViewerMutex");
 
-    if (AttachConsole(ATTACH_PARENT_PROCESS) != 0) {
-        freopen("CONIN$", "r", stdin);
-        freopen("CONOUT$", "w", stdout);
-        freopen("CONOUT$", "w", stderr);
-        dup2(fileno(stdin), STDIN_FILENO);
-        dup2(fileno(stdout), STDOUT_FILENO);
-        dup2(fileno(stderr), STDERR_FILENO);
+    /* Get redirection from parent */
+    BOOL out_valid = is_handle_valid(GetStdHandle(STD_OUTPUT_HANDLE));
+    BOOL err_valid = is_handle_valid(GetStdHandle(STD_ERROR_HANDLE));
+
+    /*
+     * If not all output are redirected try to redirect to parent console.
+     * If parent has no console (for instance as launched from GUI) just
+     * rely on default (no output).
+     */
+    if ((!out_valid || !err_valid) && AttachConsole(ATTACH_PARENT_PROCESS)) {
+        if (!out_valid) {
+            freopen("CONOUT$", "w", stdout);
+            dup2(fileno(stdout), STDOUT_FILENO);
+        }
+        if (!err_valid) {
+            freopen("CONOUT$", "w", stderr);
+            dup2(fileno(stderr), STDERR_FILENO);
+        }
     }
 
     /* Disable input method handling so that the Zenkaku_Hankaku can be passed
-- 
2.5.5



More information about the Spice-devel mailing list