func EnumProcesses()

in sys/windows/syscall_windows.go [366:405]


func EnumProcesses() ([]uint32, error) {
	enumProcesses := func(size int) ([]uint32, error) {
		var (
			pids         = make([]uint32, size)
			sizeBytes    = len(pids) * sizeofUint32
			bytesWritten uint32
		)

		err := _EnumProcesses(&pids[0], uint32(sizeBytes), &bytesWritten)

		pidsWritten := int(bytesWritten) / sizeofUint32
		if int(bytesWritten)%sizeofUint32 != 0 || pidsWritten > len(pids) {
			return nil, errors.Errorf("EnumProcesses returned an invalid bytesWritten value of %v", bytesWritten)
		}
		pids = pids[:pidsWritten]

		return pids, err
	}

	// Retry the EnumProcesses call with larger arrays if needed.
	size := 2048
	var pids []uint32
	for tries := 0; tries < 5; tries++ {
		var err error
		pids, err = enumProcesses(size)
		if err != nil {
			return nil, errors.Wrap(err, "EnumProcesses failed")
		}

		if len(pids) < size {
			break
		}

		// Increase the size the pids array and retry the enumProcesses call
		// because the array wasn't large enough to hold all of the processes.
		size *= 2
	}

	return pids, nil
}