Coverage Report

Created: 2026-05-11 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/frr/lib/pid_output.c
Line
Count
Source
1
// SPDX-License-Identifier: GPL-2.0-or-later
2
/*
3
 * Process id output.
4
 * Copyright (C) 1998, 1999 Kunihiro Ishiguro
5
 */
6
7
#include <zebra.h>
8
#include <fcntl.h>
9
#include <log.h>
10
#include "lib/version.h"
11
#include "network.h"
12
#include "lib_errors.h"
13
14
0
#define PIDFILE_MASK 0644
15
16
pid_t pid_output(const char *path)
17
0
{
18
0
  int tmp;
19
0
  int fd;
20
0
  pid_t pid;
21
0
  char buf[16];
22
0
  struct flock lock;
23
0
  mode_t oldumask;
24
25
0
  pid = getpid();
26
27
0
  oldumask = umask(0777 & ~PIDFILE_MASK);
28
0
  fd = open(path, O_RDWR | O_CREAT, PIDFILE_MASK);
29
0
  if (fd < 0) {
30
0
    flog_err_sys(EC_LIB_SYSTEM_CALL,
31
0
           "Can't create pid lock file %s (%s), exiting",
32
0
           path, safe_strerror(errno));
33
0
    umask(oldumask);
34
0
    exit(1);
35
0
  } else {
36
0
    size_t pidsize;
37
38
0
    umask(oldumask);
39
0
    memset(&lock, 0, sizeof(lock));
40
41
0
    set_cloexec(fd);
42
43
0
    lock.l_type = F_WRLCK;
44
0
    lock.l_whence = SEEK_SET;
45
46
0
    if (fcntl(fd, F_SETLK, &lock) < 0) {
47
0
      flog_err_sys(EC_LIB_SYSTEM_CALL,
48
0
             "Could not lock pid_file %s (%s), exiting.  Please ensure that the daemon is not already running",
49
0
             path, safe_strerror(errno));
50
0
      exit(1);
51
0
    }
52
53
0
    snprintf(buf, sizeof(buf), "%d\n", (int)pid);
54
0
    pidsize = strlen(buf);
55
0
    if ((tmp = write(fd, buf, pidsize)) != (int)pidsize)
56
0
      flog_err_sys(
57
0
        EC_LIB_SYSTEM_CALL,
58
0
        "Could not write pid %d to pid_file %s, rc was %d: %s",
59
0
        (int)pid, path, tmp, safe_strerror(errno));
60
0
    else if (ftruncate(fd, pidsize) < 0)
61
0
      flog_err_sys(
62
0
        EC_LIB_SYSTEM_CALL,
63
0
        "Could not truncate pid_file %s to %u bytes: %s",
64
0
        path, (unsigned int)pidsize,
65
0
        safe_strerror(errno));
66
0
  }
67
0
  return pid;
68
0
}