Go
- 2 ответа
- 0 вопросов
0
Вклад в тег
package main
import (
"bytes"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
)
func main() {
result, err := isProgrammRunning()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if result {
fmt.Println("Process is running - exit")
os.Exit(1)
}
// Code
}
func isProgrammRunning() (bool, error) {
name := os.Args[0]
if runtime.GOOS == "windows" {
cmd := exec.Command("tasklist.exe", "/fo", "csv", "/nh")
nameSplit := strings.Split(name, "\\")
name = nameSplit[len(nameSplit)-1]
out, err := cmd.Output()
if err != nil {
return false, err
}
name = "\"" + name + "\""
if bytes.Index(out, []byte(name)) != -1 && bytes.Index(out, []byte(name)) != bytes.LastIndex(out, []byte(name)) {
return true, nil
}
} else {
cmd := exec.Command("ps", "aco", "command")
nameSplit := strings.Split(name, "/")
name = nameSplit[len(nameSplit)-1]
out, err := cmd.Output()
if err != nil {
return false, err
}
str := strings.Split(string(out), "\n")
count := 0
for _, item := range str {
if name == item {
count++
}
if count == 2 {
return true, nil
}
}
}
return false, nil
}