[Spice-devel] [PATCH v2] Attempt to manage redirection in a way similar to Unix

Frediano Ziglio fziglio at redhat.com
Mon Mar 21 12:38:48 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 | 30 +++++++++++++++++++++++-------
 1 file changed, 23 insertions(+), 7 deletions(-)

Changes from v1:
- use GetStartupInfo instead of GetStdHandle to detect redirections.
  This is more compatible and works on both Windows 7 and Windows 10.

diff --git a/src/virt-viewer-util.c b/src/virt-viewer-util.c
index f2ccd13..55fe672 100644
--- a/src/virt-viewer-util.c
+++ b/src/virt-viewer-util.c
@@ -302,13 +302,29 @@ 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 */
+    STARTUPINFO si;
+    memset(&si, 0, sizeof(si));
+    si.cb = sizeof(si);
+    si.dwFlags = STARTF_USESTDHANDLES;
+    GetStartupInfo(&si);
+    gboolean out_valid = si.hStdOutput != INVALID_HANDLE_VALUE;
+    gboolean err_valid = si.hStdError  != INVALID_HANDLE_VALUE;
+
+    /*
+     * 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);
+        }
     }
 #endif
 
-- 
2.5.5



More information about the Spice-devel mailing list