github.com/sandwich-go/boost@v1.3.29/xproc/process_mgr.go (about)

     1  package xproc
     2  
     3  import (
     4  	"os"
     5  	"sync"
     6  )
     7  
     8  type Manager struct {
     9  	processes sync.Map
    10  }
    11  
    12  func NewManager() *Manager { return &Manager{} }
    13  
    14  func (m *Manager) NewProcess(path string, opt ...ProcessOption) *Process {
    15  	p := NewProcess(path, opt...)
    16  	p.Manager = m
    17  	return p
    18  }
    19  
    20  func (m *Manager) GetProcess(pid int) *Process {
    21  	if v, ok := m.processes.Load(pid); ok {
    22  		return v.(*Process)
    23  	}
    24  	return nil
    25  }
    26  
    27  func (m *Manager) AddProcess(pid int) {
    28  	if _, ok := m.processes.Load(pid); !ok {
    29  		if process, err := os.FindProcess(pid); err == nil {
    30  			p := m.NewProcess("", nil, nil)
    31  			p.Process = process
    32  			m.processes.Store(pid, p)
    33  		}
    34  	}
    35  }
    36  
    37  func (m *Manager) RemoveProcess(pid int) {
    38  	m.processes.Delete(pid)
    39  }
    40  
    41  func (m *Manager) Processes() []*Process {
    42  	processes := make([]*Process, 0)
    43  	m.processes.Range(func(key, value interface{}) bool {
    44  		processes = append(processes, value.(*Process))
    45  		return true
    46  	})
    47  	return processes
    48  }
    49  
    50  func (m *Manager) Pids() (ret []int) {
    51  	m.processes.Range(func(key, value interface{}) bool {
    52  		ret = append(ret, key.(int))
    53  		return true
    54  	})
    55  	return
    56  }
    57  
    58  func (m *Manager) WaitAll() {
    59  	processes := m.Processes()
    60  	if len(processes) > 0 {
    61  		for _, p := range processes {
    62  			p.Wait()
    63  		}
    64  	}
    65  }
    66  
    67  func (m *Manager) KillAll() error {
    68  	for _, p := range m.Processes() {
    69  		if err := p.Kill(); err != nil {
    70  			return err
    71  		}
    72  	}
    73  	return nil
    74  }
    75  
    76  func (m *Manager) SignalAll(sig os.Signal) error {
    77  	for _, p := range m.Processes() {
    78  		if err := p.Signal(sig); err != nil {
    79  			return err
    80  		}
    81  	}
    82  	return nil
    83  }
    84  func (m *Manager) Clear() {
    85  	m.processes.Range(func(key, value interface{}) bool {
    86  		m.processes.Delete(key)
    87  		return true
    88  	})
    89  }
    90  
    91  func (m *Manager) Size() (c int) {
    92  	m.processes.Range(func(key, value interface{}) bool {
    93  		c++
    94  		return true
    95  	})
    96  	return
    97  }