Attachconsole error 6

Every time I run electron-webpack dev is get the following renderer error: AttachConsole failed with error 6: The handle is invalid. Nothing I've tried has been able to remove this warning, and...

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@AaronBeaudoin

Every time I run electron-webpack dev is get the following renderer error: AttachConsole failed with error 6: The handle is invalid.

Nothing I’ve tried has been able to remove this warning, and it seems to be resulting in another warning later when I close my app: CtrlC(): GenerateConsoleCtrlEvent failed with error 6: The handle is invalid. Again, both of these warning are marked as being from the renderer process.

I’m on Windows 10 using Node 8.11.1 and electron-webpack 2.7.4.

Any help would be much appreciated.

@AaronBeaudoin
AaronBeaudoin

changed the title
AttachConsole failed Renderer Error

AttachConsole failed with error 6 Renderer Error

Jul 30, 2019

@loopmode

I usually just ignore those :) looking forward for hints and solutions tho!

@Suniron

@b-zurg

I actually don’t think this is a huge issue but it is certainly is annoying. I couldn’t find much about the error when digging through Any help would be appreciated but in the meantime it’s a working dev environment.

@loopmode

Does somebody on Mac or Linux have this issue, or is it a Windows thing?

@loopmode

I ask because I suspect this is related to runnerw.exe which is used: https://github.com/electron-userland/electron-webpack/blob/master/packages/electron-webpack/src/dev/ChildProcessManager.ts
We have this other issue of Ctrl+c not killing the webpack process correctly, which is definitely because of runnerw.exe.
And, I tried once to simply not use runnerw.exe despite of being on Windows, and it actually still worked fine for me, plus Ctrl+C killed all processes.

I’m curious to know if it helps with this warning as well. I’ll try and report if i find the time, feel free to try as well. Just edit the file in node_modules and remove the special treatment for Windows.

@Suniron

Yes it’s only on Windows for me. The same project has no error on Ubuntu or Raspbian

@b-zurg

I just tried on mac also. Totes a Windows thing.

@loopmode

Well then, as mentioned in #249 (comment) we might provide an opt-out of runnerw.exe. while it would be elegant to do it via config, it would be much much simpler via env var. And it would solve the zombie child process problem. However, I’m not sure what we would lose, apparently something about low level signal propagation. In my quick test, everything seemed to work fine but I think we should do some more testing. Since I’m currently actively working with electron-webpack again, I’ll give this some time tomorrow. Would be awesome if you guys could join in and also try it out.

(On the other hand, there’s not much to lose if it’s just an opt-out).

@loopmode

As suspected, not using runnerw.exe on windows helps.

@loopmode

If you use cmd.exe, this problem doesn’t occur. It only happens when you use e.g. git bash.

It seems that when electron-webpack checks for win32 platform, it assumes cmd.exe and launches child processes via runnerw.exe. This is good for cmd.exe, however I would bet that most or at least many developers on windows use git bash instead. Still checking if we should control this behaviour via env variable (e.g. ELECTRON_WEBPACK_USE_RUNNERW or ELECTRON_WEBPACK_SKIP_RUNNERW). It would be better to detect that we are indeed inside cmd.exe instance.

@Suniron

I have tried with cmd.exe and the problem is here also..
Same with Powershell, Cmder.
I must launch my command yarn dev in Admin mode because i’m on profesional computer..

@loopmode

Hm okay then. Hmm. Then I cannot be sure that skipping runnerw.exe will help without somebody cross-checking, seems my local situation is not reliable enough. @Suniron since you’re already taking time for this.. could you maybe check? See my link to a comment in #249 , there is a isWin check in DevRunner. You could just disable it inside installed node_modules and re-test.

@b-zurg

I just tried this out. In ChildProcessManager.js in my node_modules I changed this function

function run(program, args, options) {
  const isWin = process.platform === "win32";
  return (0, _child_process().spawn)(isWin ? path.join(__dirname, "../../vendor/runnerw.exe") : program, isWin ? [program].concat(args) : args, options);
}

to this

function run(program, args, options) {
  const isWin = process.platform === "win32";
  return (0, _child_process().spawn)(program, isWin ? [program].concat(args) : args, options);
}

and the message

┏ Renderer -------------------

  AttachConsole failed with error 6: The handle is invalid.

┗ ----------------------------

was gone. But instead the renderer failed to compile. This is on running electron-webpack dev

┏ Renderer -------------------

  i 「wdm」: Failed to compile.

┗ ----------------------------

The main bundle compiled fine funnily enough.
I’m using git bash as a side-note.

@loopmode

When I tried it, I completely removed the isWin:
return (0, _child_process().spawn)(program, args, options);
And both main and renderer seemed fine.

@obermillerk

Also having this issue. Didn’t think much of it, untli this morning when I was noticing some weird lag on my computer. Checked my task manager and there were about 2 dozen if not more rogue nodejs processes that I have since confirmed are spawned by using electronwebpack dev but not killed with the electron app or a kill signal.

I’m on Windows 10 and have been using PowerShell, but I just tried in CMD and had the same issue. @loopmode’s change fixes the issue, but I’m hoping for some official resolution to this soon since I hate modifying flies in node_modules

@msemtd

I keep revisiting this problem to see if anyone has a fix — most recently I’ve been trying to add emscripten WebAssembly code to an electron-webpack app and the stderr and stdout streams just plain do not work which makes this problem look like the culprit. I can’t be sure because I’m not smart enough to debug this stuff!

@loopmode

Hi @msemtd — well you might have the perfect test case there, since you’re working with the stderr and stdout streams explicitly. And, since you’re working with WebAssembly, you’re implicitly smart enough to try it out ;)

Could you please take a few minutes and change one line in your installed node_modules?

In the file node_modules/electron-webpack/out/dev/ChildProcessManager.js, find this line:

const isWin = process.platform === "win32";

and simply replace it with:

Then try again. Does it help?
If so, we might simply go forward and drop that ugly windows workaround using runnerw.exe. The sole purpose of that thing is to make streams work on windows..
Or at least we actually really go for a simple env flag to disable it, as proposed elsewhere (e.g. ELECTRON_WEBPACK_SKIP_RUNNERW)

@msemtd

…and simply replace it with:

Then try again. Does it help?

Sorry for the delay, yes, it does resolve the problem! [edited]

@mia1024

I had the same problem and can confirm that changing isWin to false solves the issue. However, when I tried to ctrl-c out of the process, the renderer process asks Terminate batch job (Y/N)? instead, which I had no way to respond. After a while the process seemed to have exited due to timeout.

@shadrachtuck

I’ve had this issue as well on my windows machine. I’ve tried the win32 = false trick which removes the error. Unfortunately, the app doesn’t load and the terminal just immediately says, «Done in s» as if I had pressed control C. Let me know if anyone has a solution. Works fine on my mac machine. Another reason for me to want to throw this computer in the garbage lol.

@loopmode

Heh, maybe we should just spend some time for a proper docker-based development setup and use that on Windows :)

@msemtd

Is there a release on the way that incorporates the fix?

@appurist

I’m having this problem (today). I’m not sure why the problem was closed without any resolution (other than hacking the project or forking it).

I think it eventually times out and exits, so if you’re patient it’s not a problem, but it certainly slows down my development edit-build-test cycle.

@einarpersson

Same here today! Windows 10. But after 30 sec the app started as usual. But it felt a bit sketchy

@shadrachtuck

This issue shouldn’t be closed. I haven’t gotten to run my application on my Windows machine for months because of this.

@loopmode

Glad to reopen the issue guys, but it still needs somebody that tackles and solves the problem :)

@msemtd

Is it still waiting on #249 being resolved?

@Ga-Lin

Try this one:
In the file node_modules/electron-webpack/out/dev/ChildProcessManager.js, find this line const isWin = process.platform === "win32";, change win32 to win64 may help.
Perhaps it’s not compatible with your 64 bit system.

@loopmode

@Ga-Lin

@loopmode well, you are right, I did’t read that carefully before, but something interesting happens today, when I run my application again without any changes(still use win32 and don’t change isWin), the issue doesn’t occur any more… I just reboot my computer

@loopmode

@Ga-Lin Well it’s quite weird at least in Windows. Maybe you have noticed also that on windows, processes keep stacking up after you stop the dev server (at least one cmd.exe process stays alive each time, i believe it’s actually webpack via runnerw.exe via cmd.exe). So it’s quite possible that things get better when restarting the computer :)

Btw the weirdness is only with development mode, your bundled app has no such issues.

@prcdpr

Until it’s fixed on electron-webpack side:

Inside package.json add

"scripts": {
  "postinstall": "node patch.js"
}

Create patch.js file in root directory.

// Fix for https://github.com/electron-userland/electron-webpack/issues/307

const fs = require("fs");
const path = require("path");

const cpmPath = path.join(
  __dirname,
  "node_modules",
  "electron-webpack",
  "out",
  "dev",
  "ChildProcessManager.js"
);

let script = fs.readFileSync(cpmPath).toString("utf8");
script = script.replace(
  'const isWin = process.platform === "win32";',
  "const isWin = false;"
);

fs.writeFileSync(cpmPath, script);

Armster15

added a commit
to Armster15/electron-react-template
that referenced
this issue

Apr 5, 2021

@Armster15

 
A.L.E.X.A.N.D.E.R ©
 
(2007-06-18 21:05)
[0]

Возник вопрос по поводу :
как ввести данные из своего приложения в работающее консольное приложение , т.е. типа gui
Подскажите пожалуйста .


 
SLoW.AlfaMoon.Com
 
(2007-06-19 10:21)
[1]

AttachConsole + WriteConsoleInput.


 
A.L.E.X.A.N.D.E.R ©
 
(2007-06-19 23:45)
[2]

А можно пожалуйста пример ?
просто ньюансов там многовато .


 
SLoW.AlfaMoon.Com
 
(2007-06-20 10:33)
[3]

Впрочем, я, похоже, поторопился. НАлицо наличие некоторых проблем с функцией AttachConsole.

http://www.wasm.ru/forum/viewtopic.php?pid=125645 — здесь обсуждение похожего вопроса.

ПРимер, наскоро накиданный мной:

procedure TForm1.Button1Click(Sender: TObject);
 var h,w: THandle;
     ncw,pid: dword;
     buf: array[0..5] of char;
begin
 buf[0] := "t";
 buf[1] := "e";
 buf[2] := "s";
 buf[3] := "t";
 buf[4] := #0;
 h := WinExec("cmd.exe",SW_SHOW);
 pid := GetProcessId("cmd.exe");
 if pid = 0 then begin showmessage("pid=0");exit;end;
 if AttachConsole(pid) then
 begin
   w := GetStdHandle(STD_OUTPUT_HANDLE);
   WriteConsole(w,@buf[0],4,ncw,nil);
   FreeConsole;
 end else showmessage("attach failed:"+inttostr(getlasterror));

end;

Тут получаются такие сложности. Имею запущенный cmd.exe. Проходя код под отладчиком, все получается хорошо. При запуске без отладчика AttachConsole возвращает ошибку 6 — Invalid Handle.


 
SLoW.AlfaMoon.Com
 
(2007-06-20 10:50)
[4]

Проблема банально решилась добавлением Sleep(500) после строчки с WinExec»om. Ну или экспериментируйте с CreateProcess


 
A.L.E.X.A.N.D.E.R ©
 
(2007-06-20 13:06)
[5]

А какие модули ещё надо подключить , а то Delphi у меня ругается на «GetProcessId» и на «AttachConsole» .


 
A.L.E.X.A.N.D.E.R ©
 
(2007-06-20 13:33)
[6]

c «GetProcessId» разобрался , а вот с «AttachConsole» — никак .


 
A.L.E.X.A.N.D.E.R ©
 
(2007-06-20 13:43)
[7]

хм… уже «GetProcessId» не работает …


 
clickmaker ©
 
(2007-06-20 13:43)
[8]


> [6] A.L.E.X.A.N.D.E.R ©   (20.06.07 13:33)

см. Creating a Child Process with Redirected Input and Output в MSDN


 
A.L.E.X.A.N.D.E.R ©
 
(2007-06-20 14:33)
[9]

Разобрался , спасибо .
Теперь встала ещё 1 проблема , всё что я ввожу в консольное приложение оно в нём вывожит , но оно не воспринимает этого , даже стереть , то что я написал своей программой невозможно .


 
Сергей М. ©
 
(2007-06-20 14:57)
[10]


> но оно не воспринимает этого

Что, прямо так и говорит, мол, не воспринимаю и все тут ?


> даже стереть , то что я написал своей программой невозможно

«Что написано пером —  не вырубишь …» (с)


 
SLoW.AlfaMoon.Com
 
(2007-06-20 15:00)
[11]


function AttachConsole(dwProcessId: DWORD): BOOL; stdcall; external "kernel32.dll";

function GetProcessId(pName: PChar): dword;
var
Snap: dword;
 Process: TPROCESSENTRY32;
begin
 Result := 0;
 Snap := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
 if Snap <> INVALID_HANDLE_VALUE then
    begin
     Process.dwSize := SizeOf(TPROCESSENTRY32);
     if Process32First(Snap, Process) then
        repeat
         if lstrcmpi(Process.szExeFile, pName) = 0 then
            begin
             Result := Process.th32ProcessID;
             CloseHandle(Snap);
             Exit;
            end;
        until not Process32Next(Snap, Process);
     Result := 0;
     CloseHandle(Snap);
    end;
end;


 
Сергей М. ©
 
(2007-06-20 15:07)
[12]


> SLoW.AlfaMoon.Com   (20.06.07 15:00) [11]
>
>


> GetProcessId

А ну как совсем не тот процесс твой код обнаружит ?

Мало ли м.б. процессов с указанным именем)


 
SLoW.AlfaMoon.Com
 
(2007-06-20 16:03)
[13]

Хм. Замечание верное. Тогда могу предложить недокументированное решение через Native API, только это, как мне кажется, автору не нужно. И вообще, это всего лишь пример.

Еще +1 к предложению clickmaker.


 
Сергей М. ©
 
(2007-06-20 16:09)
[14]


> SLoW.AlfaMoon.Com   (20.06.07 16:03) [13]

Не парься, уважаемый.

Просто смею рекомендовать «включать свой телепатор» тогда когда автор явно хоть чуть-чуть «шарит»


 
A.L.E.X.A.N.D.E.R ©
 
(2007-06-20 16:32)
[15]

Та епт , что делать если консольное приложение нивкакаю не воспринимает введеный в него текст ?


 
Сергей М. ©
 
(2007-06-20 16:55)
[16]


> A.L.E.X.A.N.D.E.R ©   (20.06.07 16:32) [15]


> Та епт

А нехрен, епт, влезать в работу приложения на полпути !

Стартуй его сам и управляй им через анонимный пайп — би будет тебе полное счастье ! Епт)


[built]

i 「wds」: webpack output is served from /
i 「wds」: Content not from webpack is served from d:Agora-Electron-Quickstartstatic, d:Agora-Electron-Quickstartdistrenderer-dll

i 「wdm」: Hash: dee93e32d1102e1f2dc9
Version: webpack 4.39.2
Time: 3252ms
Built at: 2019-10-09 2:51:49 PM
Asset Size Chunks Chunk Names
index.html 425 bytes [emitted]
renderer.js 4.65 MiB renderer [emitted] renderer
styles.css 210 KiB renderer [emitted] renderer
Entrypoint renderer = styles.css renderer.js
[1] multi (webpack)-dev-server/client?http://localhost:59885 (webpack)/hot/dev-server.js css-hot-loader/hotModuleReplacement ./src/renderer/index.js 64 bytes [built]
[./node_modules/bulma/css/bulma.css] 294 bytes [built]
[./node_modules/css-hot-loader/hotModuleReplacement.js] 3.05 KiB [built]
[./node_modules/css-hot-loader/node_modules/normalize-url/index.js] 3.85 KiB [built]
[./node_modules/lodash/debounce.js] 5.96 KiB [built]
[./node_modules/react-dom/index.js] 1.33 KiB [built]
[./node_modules/react/index.js] 190 bytes [built]
[./node_modules/strip-ansi/index.js] 161 bytes [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:59885] (webpack)-dev-server/client?http://localhost:59885 4.29 KiB [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.85 KiB [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes [built]
[./node_modules/webpack/hot/dev-server.js] (webpack)/hot/dev-server.js 1.59 KiB [built]
[./src/renderer/index.js] 218 bytes [built]
+ 69 hidden modules
Child html-webpack-plugin for «index.html»:
Child mini-css-extract-plugin node_modules/css-loader/dist/cjs.js??ref—6-2!src/renderer/index.css:
Entrypoint mini-css-extract-plugin = *
[./node_modules/css-loader/dist/cjs.js. /src/renderer/index.css] ./node_modules/css-loader/dist/cjs.js??ref—6-2!./src/renderer/index.css 552 bytes [built]
[./node_modules/css-loader/dist/runtime/api.js] 2.61 KiB [built]

i 「wdm」: Compiled successfully.

┗ —————————-
Error: Electron failed to install correctly, please delete node_modules/electron and try installing again
at getElectronPath (d:Agora-Electron-Quickstartnode_moduleselectronindex.js:14:11)
at Object. (d:Agora-Electron-Quickstartnode_moduleselectronindex.js:18:18)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at startElectron (d:Agora-Electron-Quickstartnode_moduleselectron-webpacksrcdevdev-runner.ts:156:33)
at DevRunner.start (d:Agora-Electron-Quickstartnode_moduleselectron-webpacksrcdevdev-runner.ts:67:5)
at process._tickCallback (internal/process/next_tick.js:68:7)

我又重新来了一遍. 上次好像是这个报错 @@我把electron删了重新装的,我现在还需要这么做么?help. Thanks.

Источник

AttachConsole failed with error 6 Renderer Error #307

Comments

AaronBeaudoin commented Jul 30, 2019

Every time I run electron-webpack dev is get the following renderer error: AttachConsole failed with error 6: The handle is invalid.

Nothing I’ve tried has been able to remove this warning, and it seems to be resulting in another warning later when I close my app: CtrlC(): GenerateConsoleCtrlEvent failed with error 6: The handle is invalid. Again, both of these warning are marked as being from the renderer process.

I’m on Windows 10 using Node 8.11.1 and electron-webpack 2.7.4.

Any help would be much appreciated.

The text was updated successfully, but these errors were encountered:

loopmode commented Jul 30, 2019

I usually just ignore those 🙂 looking forward for hints and solutions tho!

Suniron commented Nov 12, 2019

@AaronBeaudoin I have the same issue 🙁 . Did you solved it?

b-zurg commented Nov 14, 2019

I actually don’t think this is a huge issue but it is certainly is annoying. I couldn’t find much about the error when digging through Any help would be appreciated but in the meantime it’s a working dev environment.

loopmode commented Nov 14, 2019 •

Does somebody on Mac or Linux have this issue, or is it a Windows thing?

loopmode commented Nov 14, 2019 •

I ask because I suspect this is related to runnerw.exe which is used: https://github.com/electron-userland/electron-webpack/blob/master/packages/electron-webpack/src/dev/ChildProcessManager.ts
We have this other issue of Ctrl+c not killing the webpack process correctly, which is definitely because of runnerw.exe.
And, I tried once to simply not use runnerw.exe despite of being on Windows, and it actually still worked fine for me, plus Ctrl+C killed all processes.

I’m curious to know if it helps with this warning as well. I’ll try and report if i find the time, feel free to try as well. Just edit the file in node_modules and remove the special treatment for Windows.

Suniron commented Nov 14, 2019

Yes it’s only on Windows for me. The same project has no error on Ubuntu or Raspbian

b-zurg commented Nov 14, 2019

I just tried on mac also. Totes a Windows thing.

loopmode commented Nov 14, 2019 •

Well then, as mentioned in #249 (comment) we might provide an opt-out of runnerw.exe. while it would be elegant to do it via config, it would be much much simpler via env var. And it would solve the zombie child process problem. However, I’m not sure what we would lose, apparently something about low level signal propagation. In my quick test, everything seemed to work fine but I think we should do some more testing. Since I’m currently actively working with electron-webpack again, I’ll give this some time tomorrow. Would be awesome if you guys could join in and also try it out.

(On the other hand, there’s not much to lose if it’s just an opt-out).

loopmode commented Nov 18, 2019

As suspected, not using runnerw.exe on windows helps.

loopmode commented Nov 18, 2019

If you use cmd.exe , this problem doesn’t occur. It only happens when you use e.g. git bash.

It seems that when electron-webpack checks for win32 platform, it assumes cmd.exe and launches child processes via runnerw.exe . This is good for cmd.exe , however I would bet that most or at least many developers on windows use git bash instead. Still checking if we should control this behaviour via env variable (e.g. ELECTRON_WEBPACK_USE_RUNNERW or ELECTRON_WEBPACK_SKIP_RUNNERW ). It would be better to detect that we are indeed inside cmd.exe instance.

Suniron commented Nov 19, 2019

I have tried with cmd.exe and the problem is here also..
Same with Powershell, Cmder.
I must launch my command yarn dev in Admin mode because i’m on profesional computer..

loopmode commented Nov 19, 2019 •

Hm okay then. Hmm. Then I cannot be sure that skipping runnerw.exe will help without somebody cross-checking, seems my local situation is not reliable enough. @Suniron since you’re already taking time for this.. could you maybe check? See my link to a comment in #249 , there is a isWin check in DevRunner. You could just disable it inside installed node_modules and re-test.

b-zurg commented Jan 20, 2020

I just tried this out. In ChildProcessManager.js in my node_modules I changed this function

and the message

was gone. But instead the renderer failed to compile. This is on running electron-webpack dev

The main bundle compiled fine funnily enough.
I’m using git bash as a side-note.

loopmode commented Jan 25, 2020

When I tried it, I completely removed the isWin:
return (0, _child_process().spawn)(program, args, options);
And both main and renderer seemed fine.

Источник

AttachConsole function

Attaches the calling process to the console of the specified process as a client application.

Syntax

Parameters

dwProcessId [in]
The identifier of the process whose console is to be used. This parameter can be one of the following values.

Value Meaning
pid Use the console of the specified process.
ATTACH_PARENT_PROCESS (DWORD)-1 Use the console of the parent of the current process.

Return value

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

A process can be attached to at most one console. If the calling process is already attached to a console, the error code returned is ERROR_ACCESS_DENIED. If the specified process does not have a console, the error code returned is ERROR_INVALID_HANDLE. If the specified process does not exist, the error code returned is ERROR_INVALID_PARAMETER.

A process can use the FreeConsole function to detach itself from its console. If other processes share the console, the console is not destroyed, but the process that called FreeConsole cannot refer to it. A console is closed when the last process attached to it terminates or calls FreeConsole. After a process calls FreeConsole, it can call the AllocConsole function to create a new console or AttachConsole to attach to another console.

This function is primarily useful to applications that were linked with /SUBSYSTEM:WINDOWS, which implies to the operating system that a console is not needed before entering the program’s main method. In that instance, the standard handles retrieved with GetStdHandle will likely be invalid on startup until AttachConsole is called. The exception to this is if the application is launched with handle inheritance by its parent process.

To compile an application that uses this function, define _WIN32_WINNT as 0x0501 or later. For more information, see Using the Windows Headers.

Источник

Grepper Logo

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
November 13, 2020

Popularity
1/10

Helpfulness
1/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • AttachConsole failed with error 6: The handle is invalid.
  • Related Problems

  • AttachConsole failed with error 6: The handle is invalid.
  • TPC Matrix View Full Screen

    AttachConsole failed with error 6: The handle is invalid.

    Comment

    0


    Popularity

    1/10 Helpfulness
    1/10
    Language
    javascript

    Source: github.com

    Tags: handle
    javascript

    Motionless Mandrill

    Contributed on Nov 13 2020

    Motionless Mandrill

    2 Answers  Avg Quality 8/10


    Grepper

    Features
    Reviews
    Code Answers
    Search Code Snippets

    Plans & Pricing
    FAQ
    Welcome
    Browsers Supported
    Grepper Teams

    Documentation

    Adding a Code Snippet

    Viewing & Copying Snippets

    Social

    Twitter LogoTwitter

    LinkedIn LogoLinkedIn

    Legal

    Privacy Policy
    Terms

    Contact

    support@codegrepper.com

    • Remove From My Forums
    • Question

    • I know, that this question has been stated before — but I didn’t find any answer.

      Let’s take this simple example:

      

          static class Program
          {
              [DllImport("kernel32.dll")]
              [return: MarshalAs(UnmanagedType.Bool)]
              private static extern bool AttachConsole([MarshalAs(UnmanagedType.U4)] int dwProcessId);
              
              [STAThread]
              static void Main()
              {
                  if (AttachConsole(-1))
                      Console.WriteLine(@"AttachConsole() succeeded!");
                  else
                      MessageBox.Show(@"AttachConsole() failed!");
              }
          }

      When I start cmd.exe (For example by Run) — it works — I get «AttachConsole() succeeded».

      When I start it in any named window (e.g. Developer Command Prompt) — I get nothing. No console output, no message box. Moreover — when I run Marshal.GetLastWin32Error() — I get 2 (File not found).

      Is there any way to lose this problem?

    I was able to reproduce your issue and get it working on my machine. Some of your code looks like it comes from the accepted answer at No console output when using AllocConsole and target architecture x86. If you read the comment thread under that answer, you will see that new IntPtr(7) does not work as of Windows 7/ Server 2012. The «new magic number» for Windows 7 also did not work for me. To solve this, I started down the path of porting the given c++ call from the comments into c#, which required some signature changes for the PInvokes (which were all copied and pasted from PInvoke.net, so they should be fine). The changes that I made are almost exclusively in the PInvoke code. Here is a full working code set:

    Program.cs (unchanged):

    static void Main()
    {
        ServiceLauncher.RunService(() => new Service1());
    }
    

    ServiceLauncher.cs (unchanged):

    public static void RunService(Func<ServiceBase> factory)
    {
        if (Debugger.IsAttached)
        {
            Utils.AttachConsole();
            Console.Write($"Starting service ");
            var instance = factory();
            Console.WriteLine(instance.GetType().Name);
            //Invoke start Method
            Console.WriteLine("Press [ENTER] to exit");
            Console.ReadLine();
            //Stop service
        }
        else
        {
            ServiceBase.Run(factory());
        }
    }
    

    Utils.cs (1 change as documemented in comments):

    public static void AttachConsole()
    {
        var ret = NativeMethods.AllocConsole();
        IntPtr currentStdout = NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE);
    
        // IntPtr(7) was a dangerous assumption that doesn't work on current versions of Windows...
        //NativeMethods.SetStdHandle(NativeMethods.STD_OUTPUT_HANDLE, new IntPtr(7));
    
        // Instead, get the defaultStdOut using PInvoke
        SafeFileHandle defaultStdOut = NativeMethods.CreateFile("CONOUT$", EFileAccess.GenericRead | EFileAccess.GenericWrite, EFileShare.Write, IntPtr.Zero, ECreationDisposition.OpenExisting, 0, IntPtr.Zero);
        NativeMethods.SetStdHandle(NativeMethods.STD_OUTPUT_HANDLE, defaultStdOut.DangerousGetHandle());    // also seems dangerous... there may be an alternate signature for SetStdHandle that takes SafeFileHandle.
    
        TextWriter writer = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true };
        Console.SetOut(writer);
    }
    

    NativeMethods.cs (almost completely different — links and explanations given in comments). Enums included in this file (outside of the class scope) but can be moved to different files at your discretion:

    internal static class NativeMethods
    {
        // 0xFFFFFFF5 is not consistent with what I found...
        //internal const uint STD_OUTPUT_HANDLE = 0xFFFFFFF5; 
    
        // https://www.pinvoke.net/default.aspx/kernel32.getstdhandle
        internal const int STD_OUTPUT_HANDLE = -11;
    
        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool AllocConsole();
    
        // method signature changed per https://www.pinvoke.net/default.aspx/kernel32.getstdhandle
        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr GetStdHandle(int nStdHandle);
    
        // method signature changed per https://www.pinvoke.net/default.aspx/kernel32.setstdhandle
        [DllImport("kernel32.dll")]
        internal static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);
    
        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        internal static extern SafeFileHandle CreateFile(
            string lpFileName,
            EFileAccess dwDesiredAccess,
            EFileShare dwShareMode,
            IntPtr lpSecurityAttributes,
            ECreationDisposition dwCreationDisposition,
            EFileAttributes dwFlagsAndAttributes,
            IntPtr hTemplateFile);
    }
    
    
    // ENUMS FROM http://www.pinvoke.net/default.aspx/kernel32/CreateFile.html
    [Flags]
    public enum EFileAccess : uint
    {
        //
        // Standart Section
        //
    
        AccessSystemSecurity = 0x1000000,   // AccessSystemAcl access type
        MaximumAllowed = 0x2000000,     // MaximumAllowed access type
    
        Delete = 0x10000,
        ReadControl = 0x20000,
        WriteDAC = 0x40000,
        WriteOwner = 0x80000,
        Synchronize = 0x100000,
    
        StandardRightsRequired = 0xF0000,
        StandardRightsRead = ReadControl,
        StandardRightsWrite = ReadControl,
        StandardRightsExecute = ReadControl,
        StandardRightsAll = 0x1F0000,
        SpecificRightsAll = 0xFFFF,
    
        FILE_READ_DATA = 0x0001,        // file & pipe
        FILE_LIST_DIRECTORY = 0x0001,       // directory
        FILE_WRITE_DATA = 0x0002,       // file & pipe
        FILE_ADD_FILE = 0x0002,         // directory
        FILE_APPEND_DATA = 0x0004,      // file
        FILE_ADD_SUBDIRECTORY = 0x0004,     // directory
        FILE_CREATE_PIPE_INSTANCE = 0x0004, // named pipe
        FILE_READ_EA = 0x0008,          // file & directory
        FILE_WRITE_EA = 0x0010,         // file & directory
        FILE_EXECUTE = 0x0020,          // file
        FILE_TRAVERSE = 0x0020,         // directory
        FILE_DELETE_CHILD = 0x0040,     // directory
        FILE_READ_ATTRIBUTES = 0x0080,      // all
        FILE_WRITE_ATTRIBUTES = 0x0100,     // all
    
        //
        // Generic Section
        //
    
        GenericRead = 0x80000000,
        GenericWrite = 0x40000000,
        GenericExecute = 0x20000000,
        GenericAll = 0x10000000,
    
        SPECIFIC_RIGHTS_ALL = 0x00FFFF,
        FILE_ALL_ACCESS =
        StandardRightsRequired |
        Synchronize |
        0x1FF,
    
        FILE_GENERIC_READ =
        StandardRightsRead |
        FILE_READ_DATA |
        FILE_READ_ATTRIBUTES |
        FILE_READ_EA |
        Synchronize,
    
        FILE_GENERIC_WRITE =
        StandardRightsWrite |
        FILE_WRITE_DATA |
        FILE_WRITE_ATTRIBUTES |
        FILE_WRITE_EA |
        FILE_APPEND_DATA |
        Synchronize,
    
        FILE_GENERIC_EXECUTE =
        StandardRightsExecute |
            FILE_READ_ATTRIBUTES |
            FILE_EXECUTE |
            Synchronize
    }
    
    [Flags]
    public enum EFileShare : uint
    {
        /// <summary>
        /// 
        /// </summary>
        None = 0x00000000,
        /// <summary>
        /// Enables subsequent open operations on an object to request read access. 
        /// Otherwise, other processes cannot open the object if they request read access. 
        /// If this flag is not specified, but the object has been opened for read access, the function fails.
        /// </summary>
        Read = 0x00000001,
        /// <summary>
        /// Enables subsequent open operations on an object to request write access. 
        /// Otherwise, other processes cannot open the object if they request write access. 
        /// If this flag is not specified, but the object has been opened for write access, the function fails.
        /// </summary>
        Write = 0x00000002,
        /// <summary>
        /// Enables subsequent open operations on an object to request delete access. 
        /// Otherwise, other processes cannot open the object if they request delete access.
        /// If this flag is not specified, but the object has been opened for delete access, the function fails.
        /// </summary>
        Delete = 0x00000004
    }
    
    public enum ECreationDisposition : uint
    {
        /// <summary>
        /// Creates a new file. The function fails if a specified file exists.
        /// </summary>
        New = 1,
        /// <summary>
        /// Creates a new file, always. 
        /// If a file exists, the function overwrites the file, clears the existing attributes, combines the specified file attributes, 
        /// and flags with FILE_ATTRIBUTE_ARCHIVE, but does not set the security descriptor that the SECURITY_ATTRIBUTES structure specifies.
        /// </summary>
        CreateAlways = 2,
        /// <summary>
        /// Opens a file. The function fails if the file does not exist. 
        /// </summary>
        OpenExisting = 3,
        /// <summary>
        /// Opens a file, always. 
        /// If a file does not exist, the function creates a file as if dwCreationDisposition is CREATE_NEW.
        /// </summary>
        OpenAlways = 4,
        /// <summary>
        /// Opens a file and truncates it so that its size is 0 (zero) bytes. The function fails if the file does not exist.
        /// The calling process must open the file with the GENERIC_WRITE access right. 
        /// </summary>
        TruncateExisting = 5
    }
    
    [Flags]
    public enum EFileAttributes : uint
    {
        Readonly = 0x00000001,
        Hidden = 0x00000002,
        System = 0x00000004,
        Directory = 0x00000010,
        Archive = 0x00000020,
        Device = 0x00000040,
        Normal = 0x00000080,
        Temporary = 0x00000100,
        SparseFile = 0x00000200,
        ReparsePoint = 0x00000400,
        Compressed = 0x00000800,
        Offline = 0x00001000,
        NotContentIndexed = 0x00002000,
        Encrypted = 0x00004000,
        Write_Through = 0x80000000,
        Overlapped = 0x40000000,
        NoBuffering = 0x20000000,
        RandomAccess = 0x10000000,
        SequentialScan = 0x08000000,
        DeleteOnClose = 0x04000000,
        BackupSemantics = 0x02000000,
        PosixSemantics = 0x01000000,
        OpenReparsePoint = 0x00200000,
        OpenNoRecall = 0x00100000,
        FirstPipeInstance = 0x00080000
    }
    

    Понравилась статья? Поделить с друзьями:
  • Atomizer short как исправить voopoo argus
  • Auth service error
  • Atomizer short как исправить smok novo x
  • Atomizer short как исправить smok nord 4
  • Atomizer short как исправить geek vape