R
R
Roman Rakzin2016-06-04 21:23:28
go
Roman Rakzin, 2016-06-04 21:23:28

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

1 answer(s)
V
Valery Kostikov, 2016-06-13
@discip1e

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 question

Ask a Question

731 491 924 answers to any question