git: 425e4c102f8a - main - libcasper: Use pdfork() for the zygote

From: Dag-Erling Smørgrav <des_at_FreeBSD.org>
Date: Mon, 09 Nov 2026 22:14:13 UTC
The branch main has been updated by des:

URL: https://cgit.FreeBSD.org/src/commit/?id=425e4c102f8aedfc7c439bb01d648aabac798888

commit 425e4c102f8aedfc7c439bb01d648aabac798888
Author:     Dag-Erling Smørgrav <des@FreeBSD.org>
AuthorDate: 2026-11-09 22:13:42 +0000
Commit:     Dag-Erling Smørgrav <des@FreeBSD.org>
CommitDate: 2026-11-09 22:13:42 +0000

    libcasper: Use pdfork() for the zygote
    
    Use pdfork(2) rather than fork(2) to fork the zygote, and close the
    descriptor when the main loop terminates.
    
    MFC after:      1 week
    Sponsored by:   Klara, Inc.
    Sponsored by:   Qualys, Inc.
    Reviewed by:    oshogbo
    Differential Revision:  https://reviews.freebsd.org/D60176
---
 lib/libcasper/libcasper/libcasper_service.c | 12 ++++++++----
 lib/libcasper/libcasper/zygote.c            |  6 +++---
 2 files changed, 11 insertions(+), 7 deletions(-)

diff --git a/lib/libcasper/libcasper/libcasper_service.c b/lib/libcasper/libcasper/libcasper_service.c
index b951de58d229..402a266bce68 100644
--- a/lib/libcasper/libcasper/libcasper_service.c
+++ b/lib/libcasper/libcasper/libcasper_service.c
@@ -222,8 +222,9 @@ service_register_core(int fd)
 void
 casper_main_loop(int fd)
 {
+	int pfd, ret = 0;
 
-	if (zygote_init() < 0)
+	if ((pfd = zygote_init()) < 0)
 		_exit(1);
 
 	/*
@@ -232,9 +233,12 @@ casper_main_loop(int fd)
 	service_register_core(fd);
 
 	while (service_have_connections()) {
-		if (!service_poll_dispatch())
-			_exit(1);
+		if (!service_poll_dispatch()) {
+			ret = 1;
+			break;
+		}
 	}
 
-	_exit(0);
+	(void)close(pfd);
+	_exit(ret);
 }
diff --git a/lib/libcasper/libcasper/zygote.c b/lib/libcasper/libcasper/zygote.c
index 574d80a16b01..2736957e82a1 100644
--- a/lib/libcasper/libcasper/zygote.c
+++ b/lib/libcasper/libcasper/zygote.c
@@ -188,13 +188,13 @@ send:
 int
 zygote_init(void)
 {
-	int serrno, sp[2];
+	int pfd, serrno, sp[2];
 	pid_t pid;
 
 	if (socketpair(PF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0, sp) == -1)
 		return (-1);
 
-	pid = fork();
+	pid = pdfork(&pfd, PD_NOWAITPID);
 	switch (pid) {
 	case -1:
 		/* Failure. */
@@ -213,7 +213,7 @@ zygote_init(void)
 		/* Parent. */
 		zygote_sock = sp[0];
 		close(sp[1]);
-		return (0);
+		return (pfd);
 	}
 	/* NOTREACHED */
 }