netmaker/netclient/ncutils/pid.go

48 lines
1 KiB
Go
Raw Normal View History

2022-07-12 17:20:22 +08:00
package ncutils
import (
"fmt"
"os"
"strconv"
)
// PIDFILE - path/name of pid file
const PIDFILE = "/var/run/netclient.pid"
2022-07-13 23:31:32 +08:00
// WindowsPIDError - error returned from pid function on windows
type WindowsPIDError struct{}
// Error generates error for windows os
func (*WindowsPIDError) Error() string {
return "pid tracking not supported on windows"
}
2022-07-12 17:20:22 +08:00
// SavePID - saves the pid of running program to disk
func SavePID() error {
2022-07-13 01:55:35 +08:00
if IsWindows() {
2022-07-13 23:31:32 +08:00
return &WindowsPIDError{}
2022-07-13 01:55:35 +08:00
}
2022-07-12 17:20:22 +08:00
pid := os.Getpid()
2022-07-13 23:31:32 +08:00
if err := os.WriteFile(PIDFILE, []byte(fmt.Sprintf("%d", pid)), 0644); err != nil {
2022-07-12 17:20:22 +08:00
return fmt.Errorf("could not write to pid file %w", err)
}
return nil
}
// ReadPID - reads a previously saved pid from disk
func ReadPID() (int, error) {
2022-07-13 01:55:35 +08:00
if IsWindows() {
2022-07-13 23:31:32 +08:00
return 0, &WindowsPIDError{}
} else {
bytes, err := os.ReadFile(PIDFILE)
if err != nil {
return 0, fmt.Errorf("could not read pid file %w", err)
}
pid, err := strconv.Atoi(string(bytes))
if err != nil {
return 0, fmt.Errorf("pid file contents invalid %w", err)
}
return pid, nil
2022-07-13 01:55:35 +08:00
}
2022-07-12 17:20:22 +08:00
}