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

Frediano Ziglio fziglio at redhat.com
Wed Mar 2 17:11:30 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 | 29 ++++++++++++++++++++++-------
 1 file changed, 22 insertions(+), 7 deletions(-)

diff --git a/src/virt-viewer-util.c b/src/virt-viewer-util.c
index aec3b77..aba11eb 100644
--- a/src/virt-viewer-util.c
+++ b/src/virt-viewer-util.c
@@ -302,13 +302,28 @@ 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 */
+    HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
+    HANDLE err = GetStdHandle(STD_ERROR_HANDLE);
+    if (out == INVALID_HANDLE_VALUE)
+        out = NULL;
+    if (err == INVALID_HANDLE_VALUE)
+        err = NULL;
+
+    /*
+     * 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 == NULL || err == NULL) && AttachConsole(ATTACH_PARENT_PROCESS)) {
+        if (out == NULL) {
+            freopen("CONOUT$", "w", stdout);
+            dup2(fileno(stdout), STDOUT_FILENO);
+        }
+        if (err == NULL) {
+            freopen("CONOUT$", "w", stderr);
+            dup2(fileno(stderr), STDERR_FILENO);
+        }
     }
 #endif
 
-- 
2.5.0



More information about the Spice-devel mailing list