Skip to content

Commit a58f2d6

Browse files
Fix: Don't crash if the pid file contains an invalid pid (#817)
(cherry picked from commit 28d3c7c) Co-authored-by: Juan Jose Nicola <juan.nicola@greenbone.net>
1 parent aba67c1 commit a58f2d6

File tree

1 file changed

+27
-21
lines changed

1 file changed

+27
-21
lines changed

ospd/misc.py

Lines changed: 27 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,8 @@ def create_pid(pidfile: str) -> bool:
102102
"""Check if there is an already running daemon and creates the pid file.
103103
Otherwise gives an error."""
104104

105-
pid = str(os.getpid())
106-
current_process = psutil.Process(int(pid))
105+
pid = os.getpid()
106+
current_process = psutil.Process(pid)
107107
current_process_name = current_process.name()
108108

109109
pidpath = Path(pidfile)
@@ -112,33 +112,39 @@ def create_pid(pidfile: str) -> bool:
112112

113113
if pidpath.is_file():
114114
with pidpath.open('r', encoding='utf-8') as file:
115-
pf_pid = file.read()
115+
pf_pid = file.read().strip()
116116
try:
117-
process = psutil.Process(int(pf_pid))
117+
pf_pid = int(pf_pid)
118+
except (TypeError, ValueError):
119+
pf_pid = None
120+
121+
if pf_pid:
122+
try:
123+
process = psutil.Process(pf_pid)
118124
pf_process_name = process.name()
119125
except psutil.NoSuchProcess:
120126
pass
121127

122-
if pf_process_name == current_process_name and pf_pid != pid:
123-
logger.error(
124-
"There is an already running process. See %s.",
125-
str(pidpath.absolute()),
126-
)
127-
return False
128-
else:
129-
logger.debug(
130-
"There is an existing pid file '%s', but the PID %s belongs to "
131-
"the process %s. It seems that %s was abruptly stopped. "
132-
"Removing the pid file.",
133-
str(pidpath.absolute()),
134-
pf_pid,
135-
pf_process_name,
136-
current_process_name,
137-
)
128+
if pf_process_name == current_process_name and pf_pid != pid:
129+
logger.error(
130+
"There is an already running process. See %s.",
131+
str(pidpath.absolute()),
132+
)
133+
return False
134+
else:
135+
logger.debug(
136+
"There is an existing pid file '%s', but the PID %s "
137+
"belongs to the process %s. It seems that %s was "
138+
"abruptly stopped. Removing the pid file.",
139+
str(pidpath.absolute()),
140+
pf_pid,
141+
pf_process_name,
142+
current_process_name,
143+
)
138144

139145
try:
140146
with pidpath.open(mode='w', encoding='utf-8') as f:
141-
f.write(pid)
147+
f.write(str(pid))
142148
except (FileNotFoundError, PermissionError) as e:
143149
logger.error(
144150
"Failed to create pid file %s. %s", str(pidpath.absolute()), e

0 commit comments

Comments
 (0)