pidfile_unix.go

 1//go:build !windows
 2
 3package daemon
 4
 5import (
 6	"fmt"
 7	"os"
 8	"strconv"
 9	"strings"
10	"syscall"
11)
12
13// WritePID writes the current process ID to the given path.
14func WritePID(path string) error {
15	return os.WriteFile(path, []byte(strconv.Itoa(os.Getpid())), 0644)
16}
17
18// ReadPID reads the process ID from the given path.
19func ReadPID(path string) (int, error) {
20	data, err := os.ReadFile(path)
21	if err != nil {
22		return 0, err
23	}
24	pid, err := strconv.Atoi(strings.TrimSpace(string(data)))
25	if err != nil {
26		return 0, fmt.Errorf("invalid PID file: %w", err)
27	}
28	return pid, nil
29}
30
31// IsRunning checks if a daemon process is alive using the PID file.
32func IsRunning(path string) (int, bool) {
33	pid, err := ReadPID(path)
34	if err != nil {
35		return 0, false
36	}
37	// Signal 0 checks if process exists without sending a signal.
38	err = syscall.Kill(pid, 0)
39	return pid, err == nil
40}
41
42// RemovePID removes the PID file.
43func RemovePID(path string) error {
44	return os.Remove(path)
45}