github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgProcess/process.go (about)

     1  package kmgProcess
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/bronze1man/kmg/kmgCmd"
     6  	"github.com/bronze1man/kmg/kmgErr"
     7  	"github.com/bronze1man/kmg/kmgPlatform"
     8  	"github.com/bronze1man/kmg/kmgStrconv"
     9  	"github.com/bronze1man/kmg/kmgSys"
    10  	"os"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  type Process struct {
    16  	Id       int
    17  	Command  string
    18  	StartCmd string
    19  }
    20  
    21  //杀不死就算了
    22  func (p *Process) Kill() {
    23  	sysProcess, err := os.FindProcess(p.Id)
    24  	kmgErr.LogErrorWithStack(err)
    25  	err = sysProcess.Kill()
    26  	kmgErr.LogErrorWithStack(err)
    27  }
    28  
    29  func (p *Process) CmdKill() string {
    30  	return "kill " + strconv.Itoa(p.Id)
    31  }
    32  
    33  //psOutput 样例
    34  // 1234 /bin/hi -l :1024
    35  //12345 /bin/world -n test
    36  func Extract(psOutput string) []*Process {
    37  	lines := strings.Split(psOutput, "\n")
    38  	out := []*Process{}
    39  	for _, l := range lines {
    40  		ls := strings.Fields(l)
    41  		if len(ls) == 0 {
    42  			continue
    43  		}
    44  		p := &Process{
    45  			Id:      kmgStrconv.AtoIDefault0(ls[0]),
    46  			Command: strings.Join(ls[1:], " "),
    47  		}
    48  		p.StartCmd = "setsid " + p.Command
    49  		out = append(out, p)
    50  	}
    51  	return out
    52  }
    53  
    54  // 时间复杂度 2n^2
    55  func Diff(expect, running []*Process) (notExpect, notRunning []*Process) {
    56  	aHaveBNotHave := func(a, b []*Process) []*Process {
    57  		bNotHave := []*Process{}
    58  		for _, ap := range a {
    59  			isMatch := false
    60  			for _, bp := range b {
    61  				if bp.Command == ap.Command {
    62  					isMatch = true
    63  					continue
    64  				}
    65  			}
    66  			if isMatch {
    67  				continue
    68  			}
    69  			bNotHave = append(bNotHave, ap)
    70  		}
    71  		return bNotHave
    72  	}
    73  	return aHaveBNotHave(running, expect), aHaveBNotHave(expect, running)
    74  }
    75  
    76  //只兼容Linux,请用下面的那个命令
    77  func CmdProcessByBinName(binName string) string {
    78  	return fmt.Sprintf("ps -C %s -o pid=,cmd=", binName)
    79  }
    80  
    81  //以特定格式化的形式列出所有进程,方便提取进程信息
    82  //第一列是进程 ID,第二列是进程完整的执行命令(执行文件或命令+全部执行参数)
    83  //兼容:Linux, OS X
    84  func CmdAllProcess() string {
    85  	return "ps ax -o pid=,args="
    86  }
    87  
    88  func LinuxGetAllProcessByBinName(binName string) []*Process {
    89  	if !kmgPlatform.LinuxAmd64.Compatible(kmgPlatform.GetCompiledPlatform()) {
    90  		panic(kmgSys.ErrPlatformNotSupport)
    91  	}
    92  	b, err := kmgCmd.CmdBash(CmdProcessByBinName(binName)).GetExecCmd().CombinedOutput()
    93  	if err != err {
    94  		fmt.Println(err)
    95  	}
    96  	return Extract(string(b))
    97  }