Write writes a "PID file" at the specified path. It returns an error if the file exists and contains a valid PID of a running process, or when failing to write the file.
(path string, pid int)
| 53 | // file exists and contains a valid PID of a running process, or when failing |
| 54 | // to write the file. |
| 55 | func Write(path string, pid int) error { |
| 56 | if pid < 1 { |
| 57 | return fmt.Errorf("invalid PID (%d): only positive PIDs are allowed", pid) |
| 58 | } |
| 59 | oldPID, err := Read(path) |
| 60 | if err != nil && !os.IsNotExist(err) { |
| 61 | return err |
| 62 | } |
| 63 | if oldPID != 0 { |
| 64 | return fmt.Errorf("process with PID %d is still running", oldPID) |
| 65 | } |
| 66 | return os.WriteFile(path, []byte(strconv.Itoa(pid)), 0o644) |
| 67 | } |