本文整理汇总了Golang中github.com/shirou/gopsutil/process.NewProcess函数的典型用法代码示例。如果您正苦于以下问题:Golang NewProcess函数的具体用法?Golang NewProcess怎么用?Golang NewProcess使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewProcess函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: createProcesses
func (p *Procstat) createProcesses() error {
var errstring string
var outerr error
pids, err := p.getAllPids()
if err != nil {
errstring += err.Error() + " "
}
for _, pid := range pids {
_, ok := p.pidmap[pid]
if !ok {
proc, err := process.NewProcess(pid)
if err == nil {
p.pidmap[pid] = proc
} else {
errstring += err.Error() + " "
}
}
}
if errstring != "" {
outerr = fmt.Errorf("%s", errstring)
}
return outerr
}
示例2: waitForAnyPort
func (sc *ServiceCommand) waitForAnyPort(cancel <-chan struct{}, command *exec.Cmd) error {
for true {
time.Sleep(100 * time.Millisecond)
select {
case <-cancel:
return nil
default:
}
connections, err := net.Connections("all")
if err != nil {
return errors.WithStack(err)
}
proc, err := process.NewProcess(int32(command.Process.Pid))
if err != nil {
return errors.WithStack(err)
}
if hasPort(proc, connections) {
return nil
}
}
return errors.New("exited check loop unexpectedly")
}
示例3: memoryUtil
func memoryUtil() (value int64, rate float32) {
pids := apachePID()
total := make([]int64, len(pids))
var sum int64
for i, pid := range pids {
k, _ := process.NewProcess(int32(pid))
rss, _ := k.MemoryInfo()
val := rss.RSS / 1024
total[i] = int64(val)
}
for k := 0; k < len(total); k++ {
sum = sum + total[k]
}
rat := (sum / 1024) * 100
fmt.Println(sum, rat)
return sum / 1024, float32(rat)
}
示例4: pidStats
// pidStats returns the resource usage stats per pid
func (e *UniversalExecutor) pidStats() (map[string]*cstructs.ResourceUsage, error) {
stats := make(map[string]*cstructs.ResourceUsage)
e.pidLock.RLock()
pids := make(map[int]*nomadPid, len(e.pids))
for k, v := range e.pids {
pids[k] = v
}
e.pidLock.RUnlock()
for pid, np := range pids {
p, err := process.NewProcess(int32(pid))
if err != nil {
e.logger.Printf("[DEBUG] executor: unable to create new process with pid: %v", pid)
continue
}
ms := &cstructs.MemoryStats{}
if memInfo, err := p.MemoryInfo(); err == nil {
ms.RSS = memInfo.RSS
ms.Swap = memInfo.Swap
ms.Measured = ExecutorBasicMeasuredMemStats
}
cs := &cstructs.CpuStats{}
if cpuStats, err := p.Times(); err == nil {
cs.SystemMode = np.cpuStatsSys.Percent(cpuStats.System * float64(time.Second))
cs.UserMode = np.cpuStatsUser.Percent(cpuStats.User * float64(time.Second))
cs.Measured = ExecutorBasicMeasuredCpuStats
// calculate cpu usage percent
cs.Percent = np.cpuStatsTotal.Percent(cpuStats.Total() * float64(time.Second))
}
stats[strconv.Itoa(pid)] = &cstructs.ResourceUsage{MemoryStats: ms, CpuStats: cs}
}
return stats, nil
}
示例5: createProcesses
func (spec *Specification) createProcesses() ([]*process.Process, error) {
var out []*process.Process
var errstring string
var outerr error
pids, err := spec.getAllPids()
if err != nil {
errstring += err.Error() + " "
}
for _, pid := range pids {
p, err := process.NewProcess(int32(pid))
if err == nil {
out = append(out, p)
} else {
errstring += err.Error() + " "
}
}
if errstring != "" {
outerr = fmt.Errorf("%s", errstring)
}
return out, outerr
}
示例6: pidStats
// pidStats returns the resource usage stats per pid
func (e *UniversalExecutor) pidStats() (map[string]*cstructs.ResourceUsage, error) {
stats := make(map[string]*cstructs.ResourceUsage)
e.pidLock.RLock()
pids := make([]*nomadPid, len(e.pids))
copy(pids, e.pids)
e.pidLock.RUnlock()
for _, pid := range pids {
p, err := process.NewProcess(int32(pid.pid))
if err != nil {
e.logger.Printf("[DEBUG] executor: unable to create new process with pid: %v", pid.pid)
continue
}
ms := &cstructs.MemoryStats{}
if memInfo, err := p.MemoryInfo(); err == nil {
ms.RSS = memInfo.RSS
ms.Swap = memInfo.Swap
}
cs := &cstructs.CpuStats{}
if cpuStats, err := p.Times(); err == nil {
cs.SystemMode = cpuStats.System
cs.UserMode = cpuStats.User
// calculate cpu usage percent
cs.Percent = pid.cpuStats.Percent(cpuStats.Total())
}
stats[strconv.Itoa(pid.pid)] = &cstructs.ResourceUsage{MemoryStats: ms, CpuStats: cs}
}
return stats, nil
}
示例7: main
func main() {
flag.Parse()
pid, err := readIntFromFile("pid")
if err != nil {
fmt.Fprintf(os.Stderr, "error reading pid: %v\n", err)
os.Exit(254)
}
process, err := process.NewProcess(pid)
if err != nil {
fmt.Fprintf(os.Stderr, "unable to create process %d instance: %v\n", pid, err)
os.Exit(254)
}
if force {
if process.Kill() != nil {
fmt.Fprintf(os.Stderr, "unable to kill process %d: %v\n", pid, err)
os.Exit(254)
}
} else {
if process.Terminate() != nil {
fmt.Fprintf(os.Stderr, "unable to terminate process %d: %v\n", pid, err)
os.Exit(254)
}
}
}
示例8: GetComponent
// GetComponent gets statistics about this component
func GetComponent() *api.ComponentStats {
status := new(api.ComponentStats)
status.Uptime = uint64(time.Now().Sub(startTime).Seconds())
process, err := process.NewProcess(int32(os.Getpid()))
if err == nil {
if memory, err := process.MemoryInfo(); err == nil {
status.Memory = &api.ComponentStats_MemoryStats{
Memory: memory.RSS,
Swap: memory.Swap,
}
}
if cpu, err := process.Times(); err == nil {
status.Cpu = &api.ComponentStats_CPUStats{
User: float32(cpu.User),
System: float32(cpu.System),
Idle: float32(cpu.Idle),
}
}
}
status.Goroutines = uint64(runtime.NumGoroutine())
memstats := new(runtime.MemStats)
runtime.ReadMemStats(memstats)
status.GcCpuFraction = float32(memstats.GCCPUFraction)
return status
}
示例9: storeProc
// dockerData gather date from docker daemon directly (using DOCKER_HOST)
// and from proc/DOCKER_PID/status and publish those to conn
func storeProc(pidfile string, interval time.Duration) {
pid, err := loadPid(pidfile)
if err != nil {
warn(err)
return
}
p, err := process.NewProcess(int32(pid))
warn(err)
if err != nil {
return
}
// threads
threads, err := p.NumThreads()
warn(err)
if err != nil {
return
}
mi, err := p.MemoryInfo()
warn(err)
if err != nil {
return
}
procData := map[string]interface{}{"threads": threads, "vmsize": int(mi.VMS), "rss": int(mi.RSS)}
log.Println("proc = ", procData)
store("process", map[string]string{"pid": strconv.Itoa(int(pid))}, procData)
}
示例10: Status
func (sc *ServiceConfig) Status() ([]ServiceStatus, error) {
command, err := sc.GetCommand()
if err != nil {
return nil, errors.WithStack(err)
}
status := ServiceStatus{
Service: sc,
Status: "STOPPED",
}
if command.Pid != 0 {
status.Status = "RUNNING"
status.Pid = command.Pid
proc, err := process.NewProcess(int32(command.Pid))
if err != nil {
return nil, errors.WithStack(err)
}
epochStart, err := proc.CreateTime()
if err != nil {
return nil, errors.WithStack(err)
}
status.StartTime = time.Unix(epochStart/1000, 0)
status.Ports, err = sc.getPorts(proc)
if err != nil {
return nil, errors.WithStack(err)
}
}
return []ServiceStatus{
status,
}, nil
}
示例11: getProcCmdline
//Returns the command line slice for a given process name
func getProcCmdline(procname string) (cmd []string, err error) {
var proc *process.Process
pid := getProcPID(procname)
proc, err = process.NewProcess(int32(pid))
cmd, err = proc.CmdlineSlice()
return cmd, err
}
示例12: killAllChildren
func killAllChildren(pid int32) error {
p, err := process.NewProcess(pid)
if err != nil {
return err
}
processes := []*process.Process{p}
for i := 0; i < len(processes); i++ {
children, err := processes[i].Children()
if err != nil && err != process.ErrorNoChildren {
return err
}
processes = append(processes, children...)
}
for _, p := range processes {
osProcess, err := os.FindProcess(int(p.Pid))
if err != nil {
if err.Error() == "os: process already finished" {
continue
}
return err
}
err = osProcess.Kill()
if err != nil {
return err
}
}
return nil
}
示例13: Run
// Run gathers ps information from gosigar.
func (p *Ps) Run() error {
pids := sigar.ProcList{}
err := pids.Get()
if err != nil {
return err
}
for _, pid := range pids.List {
state := sigar.ProcState{}
mem := sigar.ProcMem{}
time := sigar.ProcTime{}
if err := state.Get(pid); err != nil {
continue
}
if err := mem.Get(pid); err != nil {
continue
}
if err := time.Get(pid); err != nil {
continue
}
procData := make(map[string]interface{})
procData["Name"] = state.Name
procData["Pid"] = pid
procData["ParentPid"] = state.Ppid
procData["StartTime"] = time.FormatStartTime()
procData["RunTime"] = time.FormatTotal()
procData["MemoryResident"] = mem.Resident / 1024
procData["State"] = string(state.State)
gopsutilProcess, err := gopsutil_process.NewProcess(int32(pid))
if err != nil {
continue
}
mmaps, err := gopsutilProcess.MemoryMaps(false)
if err == nil {
procData["MemoryMaps"] = mmaps
}
ios, err := gopsutilProcess.IOCounters()
if err == nil {
procData["IOCounters"] = ios
}
ctxSwitches, err := gopsutilProcess.NumCtxSwitches()
if err == nil {
procData["CtxSwitches"] = ctxSwitches
}
if len(procData) > 0 {
p.Data[strconv.Itoa(pid)] = procData
}
}
return nil
}
示例14: runCpuMonitor
func runCpuMonitor(monitor *CpuLoadMonitor) {
pid := os.Getpid()
process, _ := process.NewProcess(int32(pid))
for monitor.running {
monitor.sample, _ = process.CPUPercent(0)
monitor.cpu = monitor.alpha*monitor.sample + (1-monitor.alpha)*monitor.cpu
time.Sleep(monitor.samplingInterval)
}
}
示例15: ProcessStats
func (ds *DaemonStat) ProcessStats() {
ds.PointsRate = float64(ds.PointsCounter) / float64(ds.Interval)
p, err := process.NewProcess(int32(os.Getpid()))
if err == nil {
ds.MemGauge, _ = p.MemoryInfo()
} else {
ds.MemGauge = nil
log.Errorf("%v", err)
Stat.ErrorIncr()
}
}