Krolyxon
Commit 658a935

Branches

Refs →

nsxiv658a935

fix: potentially printing wrong error message (#321)

it's possible for the close() calls to override the errno resulting in
incorrect error message being printed.

call error() immediately to avoid such possibilities.

also refactor a couple conditions to avoid doing multiple checks.
Author
NRK
Date
2022-06-25 08:21 +0200
Parent
9812d60
Commit
658a935c04ba6dd1bfb370ad0e209046dd90402f

+17 −22

2 files changed

  1. M main.c +1 −1
  2. M util.c +16 −21
M main.c View
@@ -567,8 +567,8 @@ static bool run_key_handler(const char *key, unsigned int mask)
567567 if (pfd.writefd < 0)
568568 return false;
569569 if ((pfs = fdopen(pfd.writefd, "w")) == NULL) {
570− close(pfd.writefd);
571570 error(0, errno, "open pipe");
571+ close(pfd.writefd);
572572 return false;
573573 }
574574
M util.c View
@@ -233,8 +233,7 @@ spawn_t spawn(const char *cmd, char *const argv[], unsigned int flags)
233233 {
234234 pid_t pid;
235235 spawn_t status = { -1, -1, -1 };
236− int pfd_read[2] = { -1, -1 };
237− int pfd_write[2] = { -1, -1 };
236+ int pfd_read[2] = { -1, -1 }, pfd_write[2] = { -1, -1 };
238237 const bool r = flags & X_READ;
239238 const bool w = flags & X_WRITE;
240239
@@ -247,16 +246,18 @@ spawn_t spawn(const char *cmd, char *const argv[], unsigned int flags)
247246 }
248247
249248 if (w && pipe(pfd_write) < 0) {
249+ error(0, errno, "pipe: %s", cmd);
250250 if (r) {
251251 close(pfd_read[0]);
252252 close(pfd_read[1]);
253253 }
254− error(0, errno, "pipe: %s", cmd);
255254 return status;
256255 }
257256
258− if ((pid = fork()) == 0) {
259− bool err = (r && dup2(pfd_read[1], 1) < 0) || (w && dup2(pfd_write[0], 0) < 0);
257+ if ((pid = fork()) == 0) { /* in child */
258+ if ((r && dup2(pfd_read[1], 1) < 0) || (w && dup2(pfd_write[0], 0) < 0))
259+ error(EXIT_FAILURE, errno, "dup2: %s", cmd);
260+
260261 if (r) {
261262 close(pfd_read[0]);
262263 close(pfd_read[1]);
@@ -265,29 +266,23 @@ spawn_t spawn(const char *cmd, char *const argv[], unsigned int flags)
265266 close(pfd_write[0]);
266267 close(pfd_write[1]);
267268 }
268−
269− if (err)
270− error(EXIT_FAILURE, errno, "dup2: %s", cmd);
271269 execv(cmd, argv);
272270 error(EXIT_FAILURE, errno, "exec: %s", cmd);
273− }
274−
275− if (r)
276− close(pfd_read[1]);
277− if (w)
278− close(pfd_write[0]);
279−
280− if (pid < 0) {
271+ } else if (pid < 0) { /* fork failed */
272+ error(0, errno, "fork: %s", cmd);
281273 if (r)
282274 close(pfd_read[0]);
283275 if (w)
284276 close(pfd_write[1]);
285− error(0, errno, "fork: %s", cmd);
286− return status;
277+ } else { /* in parent */
278+ status.pid = pid;
279+ status.readfd = pfd_read[0];
280+ status.writefd = pfd_write[1];
287281 }
288282
289− status.pid = pid;
290− status.readfd = pfd_read[0];
291− status.writefd = pfd_write[1];
283+ if (r)
284+ close(pfd_read[1]);
285+ if (w)
286+ close(pfd_write[0]);
292287 return status;
293288 }