Created
December 31, 2024 01:51
-
-
Save misterunix/4a76fa4b38e99a25cd1808ce6937418f to your computer and use it in GitHub Desktop.
Check if the program is already running. This is to get around doing deamons in Go and use crontab as a hack.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Check to see if the program is already running. returns true if it is or false if it is not. | |
func amIrunning(myname string) bool { | |
currentpid := os.Getpid() // Get the current process ID | |
currentpidStr := strconv.Itoa(currentpid) // Convert the current process ID to a string | |
cmd := exec.Command("ps", "aux") // Run the ps aux command to get a list of all running processes | |
out, err := cmd.CombinedOutput() // Get the output of the command, both srtdout and stderr | |
if err != nil { | |
ErrorLogger.Println("Error running ps aux", err) | |
panic(err) // If there is an error, panic. Dont like doing this. | |
} | |
found := false // Set the found flag to false as we have not found the program running yet | |
lines := strings.Split(string(out), "\n") // Split the output of the ps aux command into lines | |
// Loop through each line of the output | |
for _, line := range lines { | |
subs := strings.Fields(line) // Split the line into fields. This skips multi blank seperators. | |
if len(subs) < 10 { // If there are less than 10 fields, skip this line | |
continue | |
} | |
prgname := filepath.Base(strings.TrimSpace(subs[10])) // Get the program name from the 10th field | |
prgpid := strings.TrimSpace(subs[1]) // Get the process ID from the 2nd field | |
// The order of the checks is very important | |
// Check if the program's pid is the same as the current output of 'ps aux' | |
if prgpid == currentpidStr { | |
//InfoLogger.Println("Found my own pid", prgpid, currentpidStr) | |
continue // It is the same, so skip this line | |
} | |
//InfoLogger.Println("Checking", prgname, myname) | |
// Check if the program name is the same as the current program name | |
if prgname == myname { | |
found = true // Set the found flag to true | |
break // Break out of the loop | |
} | |
} | |
return found // Return the found flag | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment