[hackers] [sbase][PATCH] flock: call exec without forking

From: Arthur Williams <taaparthur_AT_disroot.org>
Date: Fri, 4 Mar 2022 01:11:00 -0600

Previously the code forked, waited for the child to exit and then
returned the child's exit code. It is simpler to just skip fork and call
exec directly.
---
 flock.c | 36 ++++++++----------------------------
 1 file changed, 8 insertions(+), 28 deletions(-)
diff --git a/flock.c b/flock.c
index fc2b6ed..367c94c 100644
--- a/flock.c
+++ b/flock.c
_AT_@ -18,8 +18,7 @@ usage(void)
 int
 main(int argc, char *argv[])
 {
-	int fd, status, savederrno, flags = LOCK_EX, nonblk = 0, oflag = 0;
-	pid_t pid;
+	int fd, savederrno, flags = LOCK_EX, nonblk = 0, oflag = 0;
 
 	ARGBEGIN {
 	case 'n':
_AT_@ -53,30 +52,11 @@ main(int argc, char *argv[])
 		eprintf("flock:");
 	}
 
-	switch ((pid = fork())) {
-	case -1:
-		eprintf("fork:");
-	case 0:
-		if (oflag && close(fd) < 0)
-			eprintf("close:");
-		argv++;
-		execvp(*argv, argv);
-		savederrno = errno;
-		weprintf("execvp %s:", *argv);
-		_exit(126 + (savederrno == ENOENT));
-	default:
-		break;
-	}
-	if (waitpid(pid, &status, 0) < 0)
-		eprintf("waitpid:");
-
-	if (close(fd) < 0)
-		eprintf("close:");
-
-	if (WIFSIGNALED(status))
-		return 128 + WTERMSIG(status);
-	if (WIFEXITED(status))
-		return WEXITSTATUS(status);
-
-	return 0;
+    if (oflag && close(fd) < 0)
+        eprintf("close:");
+    argv++;
+    execvp(*argv, argv);
+    savederrno = errno;
+    weprintf("execvp %s:", *argv);
+    _exit(126 + (savederrno == ENOENT));
 }
-- 
2.34.1
Received on Fri Mar 04 2022 - 08:11:00 CET

This archive was generated by hypermail 2.3.0 : Fri Mar 04 2022 - 08:12:35 CET