2016-03-31 20 views
5

Tôi muốn lấy id quá trình theo tên quy trình trong môi trường cửa sổ?Cách golang lấy id tiến trình theo tên quy trình?

Tôi tìm thấy golang chỉ có api os.FindProcess(id), nhưng không có tên.

+0

Bạn có thể thực hiện 'tasklist.exe' bên trong chương trình golang của bạn và xử lý đầu ra trong golang để tìm tên quá trình. – Griffin

Trả lời

1

Bạn có thể liệt kê tất cả các quy trình và khớp với tên bạn muốn tìm, bằng cách sử dụng gói cuộc gọi sys đã cập nhật, https://godoc.org/golang.org/x/sys, nó có hầu hết các cửa sổ api.

func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error) 
func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error) 

cũng thấy các tài liệu MSDN: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684834(v=vs.85).aspx

1

Tôi đã phải đấu tranh với điều này quá, và tìm thấy đường đến giải pháp không phải là rất đơn giản, bởi vì ... WINAPI :)

Cuối cùng bạn phải tạo ảnh chụp nhanh của danh sách quy trình cửa sổ hiện tại bằng cách sử dụng CreateToolhelp32Snapshot. Sau đó, bạn sẽ có được quá trình đầu tiên trong ảnh chụp nhanh với Process32First. Sau đó tiếp tục lặp qua danh sách với Process32Next, cho đến khi bạn gặp lỗi ERROR_NO_MORE_FILES. Chỉ sau đó bạn có toàn bộ danh sách quy trình.

Xem how2readwindowsprocesses để biết ví dụ làm việc.

Dưới đây là các ý chính:

const TH32CS_SNAPPROCESS = 0x00000002 

type WindowsProcess struct { 
    ProcessID  int 
    ParentProcessID int 
    Exe    string 
} 

func processes() ([]WindowsProcess, error) { 
    handle, err := windows.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) 
    if err != nil { 
     return nil, err 
    } 
    defer windows.CloseHandle(handle) 

    var entry windows.ProcessEntry32 
    entry.Size = uint32(unsafe.Sizeof(entry)) 
    // get the first process 
    err = windows.Process32First(handle, &entry) 
    if err != nil { 
     return nil, err 
    } 

    results := make([]WindowsProcess, 0, 50) 
    for { 
     results = append(results, newWindowsProcess(&entry)) 

     err = windows.Process32Next(handle, &entry) 
     if err != nil { 
      // windows sends ERROR_NO_MORE_FILES on last process 
      if err == syscall.ERROR_NO_MORE_FILES { 
       return results, nil 
      } 
      return nil, err 
     } 
    } 
} 

func findProcessByName(processes []WindowsProcess, name string) *WindowsProcess { 
    for _, p := range processes { 
     if strings.ToLower(p.Exe) == strings.ToLower(name) { 
      return &p 
     } 
    } 
    return nil 
} 

func newWindowsProcess(e *windows.ProcessEntry32) WindowsProcess { 
    // Find when the string ends for decoding 
    end := 0 
    for { 
     if e.ExeFile[end] == 0 { 
      break 
     } 
     end++ 
    } 

    return WindowsProcess{ 
     ProcessID:  int(e.ProcessID), 
     ParentProcessID: int(e.ParentProcessID), 
     Exe:    syscall.UTF16ToString(e.ExeFile[:end]), 
    } 
} 
Các vấn đề liên quan