Skip to content

Instantly share code, notes, and snippets.

@chris-ramon
Forked from y-abe/killatom.go
Last active August 29, 2015 14:15
Show Gist options
  • Select an option

  • Save chris-ramon/65576c498b9e8ebd249a to your computer and use it in GitHub Desktop.

Select an option

Save chris-ramon/65576c498b9e8ebd249a to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"fmt"
"log"
"os/exec"
"strconv"
)
// ExecPs returns output of ps aux command
func ExecPs() ([][]byte, error) {
buf, err := exec.Command("ps", "aux").Output()
if err != nil {
return nil, err
}
out := bytes.Split(buf, []byte("\n"))
return out, nil
}
// Filter extracts Atom processes
func Filter(rows [][]byte) [][]byte {
var out [][]byte
for _, buf := range rows {
if bytes.Contains(buf, []byte("/Applications/Atom.app")) {
out = append(out, buf)
}
}
return out
}
// GetPid extracts process ID from ps output
func GetPid(rows [][]byte) ([]int, error) {
out := []int{}
for _, buf := range rows {
buf = bytes.Fields(buf)[1]
sbuf := string(buf)
ibuf, err := strconv.Atoi(sbuf)
if err != nil {
return nil, err
}
out = append(out, ibuf)
}
return out, nil
}
// KillProcess executes kill command for given process id
func KillProcess(pid int) error {
cmd := exec.Command("kill", strconv.Itoa(pid))
fmt.Println("kill " + strconv.Itoa(pid))
err := cmd.Run()
return err
}
func main() {
// execute ps aux command
out, err := ExecPs()
if err != nil {
log.Fatal(err)
}
// extract the result with Atom process
out = Filter(out)
// get process ID
pids, err := GetPid(out)
if err != nil {
log.Fatal(err)
}
// execute kill command for IDs of the Atom processes
for _, pid := range pids {
err = KillProcess(pid)
if err != nil {
log.Fatal(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment