Subject: bug#55441: [PATCH] guix: inferior: Make open-bidirectional-pipe use piped-process.

From: Josselin Poiret <[email-masked]>
Date: Thu, 26 May 2022 22:50:16 +0200

* guix/inferior.scm: Load up scm_init_popen extension to be able to
use piped-process.
(open-bidirectional-pipe): Remove custom fork+exec code and use
piped-process instead.
---
 guix/inferior.scm | 39 ++++++++++++++++++---------------------
 1 file changed, 18 insertions(+), 21 deletions(-)

diff --git a/guix/inferior.scm b/guix/inferior.scm
index 54200b75e4..a4a4c1d40e 100644
--- a/guix/inferior.scm
+++ b/guix/inferior.scm
@@ -134,6 +134,10 @@ (define (write-inferior inferior port)
 
 (set-record-type-printer! <inferior> write-inferior)
 
+(eval-when (expand load eval)
+  (load-extension (string-append "libguile-" (effective-version))
+                  "scm_init_popen"))
+
 (define (open-bidirectional-pipe command . args)
   "Open a bidirectional pipe to COMMAND invoked with ARGS and return it, as a
 regular file port (socket).
@@ -147,27 +151,20 @@ (define (open-bidirectional-pipe command . args)
   ;; the REPL process wouldn't get EOF on standard input.
   (match (socketpair AF_UNIX (logior SOCK_STREAM SOCK_CLOEXEC) 0)
     ((parent . child)
-     (match (primitive-fork)
-       (0
-        (dynamic-wind
-          (lambda ()
-            #t)
-          (lambda ()
-            (close-port parent)
-            (close-fdes 0)
-            (close-fdes 1)
-            (dup2 (fileno child) 0)
-            (dup2 (fileno child) 1)
-            ;; Mimic 'open-pipe*'.
-            (unless (file-port? (current-error-port))
-              (close-fdes 2)
-              (dup2 (open-fdes "/dev/null" O_WRONLY) 2))
-            (apply execlp command command args))
-          (lambda ()
-            (primitive-_exit 127))))
-       (pid
-        (close-port child)
-        (values parent pid))))))
+     (let* ((proc
+             (lambda ()
+               (piped-process command args
+                              ;; Use port->fdes on child to increase the
+                              ;; revealed count, so that the fd does not get
+                              ;; closed again when child gets gc'd, as
+                              ;; piped-process already closes it.
+                              (cons (fileno parent) (port->fdes child))
+                              (cons (fileno child) (fileno parent)))))
+            (pid
+             (if (file-port? (current-error-port))
+                 (proc)
+                 (with-error-to-file "/dev/null" proc))))
+       (values parent pid)))))
 
 (define* (inferior-pipe directory command error-port)
   "Return two values: an input/output pipe on the Guix instance in DIRECTORY
-- 
2.36.0