-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconsole_windows.go
More file actions
53 lines (46 loc) · 1.29 KB
/
console_windows.go
File metadata and controls
53 lines (46 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main
import (
"errors"
"log"
"os"
"syscall"
"github.com/roffe/gocan/pkg/w32"
)
const (
ATTACH_PARENT_PROCESS = ^uint32(0) // (DWORD)-1
)
var (
procAttachConsole = w32.Modkernel32.MustFindProc("AttachConsole")
oldStdin, oldStdout, oldStderr = os.Stdin, os.Stdout, os.Stderr //lint:ignore U1000 Prevent GC of the original std handles
)
func InitConsole() {
ok, err := attachConsole(ATTACH_PARENT_PROCESS)
if ok {
log.Println("attaching console")
hout, err1 := syscall.GetStdHandle(syscall.STD_OUTPUT_HANDLE)
if err1 != nil {
log.Printf("stdout connection error : %v", err1)
}
herr, err2 := syscall.GetStdHandle(syscall.STD_ERROR_HANDLE)
if err2 != nil {
log.Printf("stderr connection error : %v", err2)
}
os.Stdout = os.NewFile(uintptr(hout), "/dev/stdout")
os.Stderr = os.NewFile(uintptr(herr), "/dev/stderr")
log.SetOutput(os.Stderr)
log.Println("attached console")
return
}
if err != nil {
if errors.Is(err, syscall.Errno(5)) {
// Access denied means already attached to a console
return
}
log.Printf("attachConsole failed: %v", err)
}
}
func attachConsole(dwParentProcess uint32) (ok bool, lasterr error) {
r1, _, lasterr := syscall.SyscallN(procAttachConsole.Addr(), uintptr(dwParentProcess), 0, 0)
ok = bool(r1 != 0)
return
}