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

From: Arthur Williams <taaparthur_AT_disroot.org>
Date: Fri, 31 Dec 2021 12:28:41 -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 Dec 31 2021 - 19:28:41 CET

This archive was generated by hypermail 2.3.0 : Fri Dec 31 2021 - 19:36:31 CET