//go:build windows package host import ( "context" "errors" "fmt" "strings" "syscall" "unsafe" ) var ( procWaitForSingleObject = kernel32.NewProc("WaitForSingleObject") procQueryFullProcessImageNameW = kernel32.NewProc("QueryFullProcessImageNameW") ) const ( processSynchronize = 0x00100000 errorInvalidParameter syscall.Errno = 87 // ERROR_INVALID_PARAMETER: no process with that PID waitObject0 = 0x00000000 waitTimeoutCode = 0x00000102 // waitSliceMs is how long one wait blocks before checking ctx; the exit // itself is reported the moment it happens. waitSliceMs = 1000 ) // ErrOtherProcess: the PID now names a process other than the one expected. var ErrOtherProcess = errors.New("pid belongs to another process") // WaitProcessExit blocks until process pid exits and returns nil, or returns // ctx.Err() once ctx ends. A process already gone counts as exited. When // imageSuffix is set the process's image path must end with it (case // insensitive), else ErrOtherProcess: a guard against a reused PID. func WaitProcessExit(ctx context.Context, pid uint32, imageSuffix string) error { if pid == 0 { return errors.New("no pid") } h, _, err := procOpenProcess.Call(uintptr(processSynchronize|processQueryLimitedInfo), 0, uintptr(pid)) if h == 0 { if errno, ok := err.(syscall.Errno); ok && errno == errorInvalidParameter { return nil // no such process: it has exited } return fmt.Errorf("open process %d: %w", pid, err) } defer procCloseHandle.Call(h) // An exited process another handle keeps alive opens fine but has no // image name to read: settle that first. if r, _, _ := procWaitForSingleObject.Call(h, 0); r == waitObject0 { return nil } if imageSuffix != "" { var buf [syscall.MAX_PATH * 2]uint16 size := uint32(len(buf)) if r, _, err := procQueryFullProcessImageNameW.Call(h, 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(unsafe.Pointer(&size))); r == 0 { return fmt.Errorf("image name of process %d: %w", pid, err) } if !strings.HasSuffix(strings.ToLower(syscall.UTF16ToString(buf[:size])), strings.ToLower(imageSuffix)) { return ErrOtherProcess } } for { r, _, err := procWaitForSingleObject.Call(h, waitSliceMs) switch r { case waitObject0: return nil case waitTimeoutCode: if ctx.Err() != nil { return ctx.Err() } default: return fmt.Errorf("wait for process %d: %w", pid, err) } } }