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"
15 static void AssignStdHandle(const char* aPath
, const char* aMode
, FILE* aStream
,
17 // Visual Studio's _fileno() returns -2 for the standard
18 // streams if they aren't associated with an output stream.
19 const int fd
= _fileno(aStream
);
21 freopen(aPath
, aMode
, aStream
);
28 const HANDLE handle
= reinterpret_cast<HANDLE
>(_get_osfhandle(fd
));
29 if (handle
== INVALID_HANDLE_VALUE
) {
33 const HANDLE oldHandle
= GetStdHandle(aStdHandle
);
34 if (handle
== oldHandle
) {
38 SetStdHandle(aStdHandle
, handle
);
41 // This code attaches the process to the appropriate console.
42 void UseParentConsole() {
43 if (AttachConsole(ATTACH_PARENT_PROCESS
)) {
44 // Redirect the standard streams to the existing console, but
45 // only if they haven't been redirected to a valid file.
46 AssignStdHandle("CONOUT$", "w", stdout
, STD_OUTPUT_HANDLE
);
47 // There is no CONERR$, so use CONOUT$ for stderr as well.
48 AssignStdHandle("CONOUT$", "w", stderr
, STD_ERROR_HANDLE
);
49 AssignStdHandle("CONIN$", "r", stdin
, STD_INPUT_HANDLE
);
53 } // namespace mozilla