|
| 1 | +// Copyright 2025 The gVisor Authors. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package cmd |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "os" |
| 20 | + "path/filepath" |
| 21 | + "strconv" |
| 22 | +) |
| 23 | + |
| 24 | +// WritePidFile writes pid file atomically if possible. |
| 25 | +func WritePidFile(path string, pid int) error { |
| 26 | + pidStr := []byte(strconv.Itoa(pid)) |
| 27 | + |
| 28 | + st, err := os.Stat(path) |
| 29 | + if err == nil && !st.Mode().IsRegular() { |
| 30 | + // If not regular file, write in place. |
| 31 | + if err := os.WriteFile(path, pidStr, 0644); err != nil { |
| 32 | + return fmt.Errorf("failed to write pid file %s: %w", path, err) |
| 33 | + } |
| 34 | + return nil |
| 35 | + } |
| 36 | + if err != nil && !os.IsNotExist(err) { |
| 37 | + return fmt.Errorf("stat file %s failed: %w", path, err) |
| 38 | + } |
| 39 | + |
| 40 | + // Otherwise write using temp file to make write atomic. |
| 41 | + dir := filepath.Dir(path) |
| 42 | + tempFile, err := os.CreateTemp(dir, "pid-tmp-*") |
| 43 | + if err != nil { |
| 44 | + return fmt.Errorf("failed to create temp pid file in dir %s: %w", dir, err) |
| 45 | + } |
| 46 | + |
| 47 | + tempFileRenamed := false |
| 48 | + defer func(tempFile *os.File) { |
| 49 | + _ = tempFile.Close() |
| 50 | + if !tempFileRenamed { |
| 51 | + _ = os.Remove(tempFile.Name()) |
| 52 | + } |
| 53 | + }(tempFile) |
| 54 | + |
| 55 | + if err := os.Chmod(tempFile.Name(), 0644); err != nil { |
| 56 | + return fmt.Errorf("failed to chmod pid file %s: %w", tempFile.Name(), err) |
| 57 | + } |
| 58 | + |
| 59 | + if _, err := tempFile.Write(pidStr); err != nil { |
| 60 | + return fmt.Errorf("failed to write pid file %s: %w", tempFile.Name(), err) |
| 61 | + } |
| 62 | + |
| 63 | + if err := tempFile.Close(); err != nil { |
| 64 | + return fmt.Errorf("failed to close temp pid file %s: %w", tempFile.Name(), err) |
| 65 | + } |
| 66 | + |
| 67 | + if err := os.Rename(tempFile.Name(), path); err != nil { |
| 68 | + return fmt.Errorf("failed to rename temp pid file %s -> %s: %w", tempFile.Name(), path, err) |
| 69 | + } |
| 70 | + tempFileRenamed = true |
| 71 | + |
| 72 | + return nil |
| 73 | +} |
0 commit comments