1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "WindowsConsole.h"
13 static void AssignStdHandle(const char* aPath
, const char* aMode
, FILE* aStream
,
15 // Visual Studio's _fileno() returns -2 for the standard
16 // streams if they aren't associated with an output stream.
17 const int fd
= _fileno(aStream
);
19 freopen(aPath
, aMode
, aStream
);
26 const HANDLE handle
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
27 if (handle
== INVALID_HANDLE_VALUE
) {
31 const HANDLE oldHandle
= GetStdHandle(aStdHandle
);
32 if (handle
== oldHandle
) {
36 SetStdHandle(aStdHandle
, handle
);
39 // This code attaches the process to the appropriate console.
40 void UseParentConsole() {
41 if (AttachConsole(ATTACH_PARENT_PROCESS
)) {
42 // Redirect the standard streams to the existing console, but
43 // only if they haven't been redirected to a valid file.
44 AssignStdHandle("CONOUT$", "w", stdout
, STD_OUTPUT_HANDLE
);
45 // There is no CONERR$, so use CONOUT$ for stderr as well.
46 AssignStdHandle("CONOUT$", "w", stderr
, STD_ERROR_HANDLE
);
47 AssignStdHandle("CONIN$", "r", stdin
, STD_INPUT_HANDLE
);
51 } // namespace mozilla