From d55190c65e4cbdd8f81992ae842581a253b5ece6 Mon Sep 17 00:00:00 2001
From: Qian Hong <qhong@codeweavers.com>
Date: Sat, 22 Aug 2015 11:21:32 +0800
Subject: msvcrt: Implemenent refcount check for stdout and stderr.

---
 dlls/msvcrt/file.c       | 15 +++++++++------
 dlls/msvcrt/tests/file.c |  6 ------
 2 files changed, 9 insertions(+), 12 deletions(-)

diff --git a/dlls/msvcrt/file.c b/dlls/msvcrt/file.c
index f304ec4..49cd4f0 100644
--- a/dlls/msvcrt/file.c
+++ b/dlls/msvcrt/file.c
@@ -1007,18 +1007,21 @@ int CDECL MSVCRT__fflush_nolock(MSVCRT_FILE* file)
 int CDECL MSVCRT__close(int fd)
 {
   ioinfo *info = get_ioinfo(fd);
-  int ret;
+  int ret = 0;
 
   TRACE(":fd (%d) handle (%p)\n", fd, info->handle);
   if (!(info->wxflag & WX_OPEN)) {
     ret = -1;
   } else {
-    ret = CloseHandle(info->handle) ? 0 : -1;
-    msvcrt_free_fd(fd);
-    if (ret) {
-      WARN(":failed-last error (%d)\n",GetLastError());
-      msvcrt_set_errno(GetLastError());
+    if ((fd != MSVCRT_STDOUT_FILENO && fd != MSVCRT_STDERR_FILENO) ||
+         get_ioinfo_nolock(MSVCRT_STDOUT_FILENO)->handle != get_ioinfo_nolock(MSVCRT_STDERR_FILENO)->handle) {
+      ret = CloseHandle(info->handle) ? 0 : -1;
+      if (ret) {
+        WARN(":failed-last error (%d)\n",GetLastError());
+        msvcrt_set_errno(GetLastError());
+      }
     }
+    msvcrt_free_fd(fd);
   }
   release_ioinfo(info);
   return ret;
diff --git a/dlls/msvcrt/tests/file.c b/dlls/msvcrt/tests/file.c
index 7a79cb7..ea7d307 100644
--- a/dlls/msvcrt/tests/file.c
+++ b/dlls/msvcrt/tests/file.c
@@ -1380,23 +1380,18 @@ static void test_file_refcount_child(void)
     ret = fclose(stdout);
     ok(ret == 0, "fclose failed\n");
     ret = GetHandleInformation(h1, &flags);
-todo_wine
     ok(ret, "GetHandleInformation failed\n");
     ret = WriteFile(h1, buffer2, strlen(buffer2), &written, 0);
-todo_wine
     ok(ret, "WriteFile failed\n");
 
     ret = fclose(stdout);
     ok(ret != 0, "fclose should fail\n");
     ret = GetHandleInformation(h1, &flags);
-todo_wine
     ok(ret, "GetHandleInformation failed\n");
     ret = WriteFile(h1, buffer3, strlen(buffer3), &written, 0);
-todo_wine
     ok(ret, "WriteFile failed\n");
 
     ret = fclose(stderr);
-todo_wine
     ok(ret == 0, "fclose failed\n");
     ret = GetHandleInformation(h1, &flags);
     ok(!ret, "GetHandleInformation should fail\n");
@@ -1501,7 +1496,6 @@ static void test_file_refcount( STARTUPINFOA *startup, char *cmdline, const char
     winetest_wait_child_process( proc.hProcess );
 
     data = read_file( hMixFile );
-todo_wine
     ok( !strcmp( data, "test1test2test3" ), "%s: Wrong error data (%s)\n", descr, data );
 
     CloseHandle( hMixFile );
-- 
2.5.0

