Answer the question
In order to leave comments, you need to log in
How to prevent a golang program from opening at the same time?
How to prevent a golang program from opening at the same time?
Answer the question
In order to leave comments, you need to log in
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
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question