This essentially just does a fork() + setsid().
Needed to e.g. properly spawn background processes.

Signed-off-by: Christoph Heiss <c.he...@proxmox.com>
---
Something similar is already used in e.g. pve-storage to spawn fuse
mounts. If and when this is applied, I'd migrate these sites to this sub
too.

 src/PVE/Tools.pm | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/src/PVE/Tools.pm b/src/PVE/Tools.pm
index 0325f53..f5bf24a 100644
--- a/src/PVE/Tools.pm
+++ b/src/PVE/Tools.pm
@@ -1117,6 +1117,36 @@ sub run_fork {
     return run_fork_with_timeout(undef, $code, $opts);
 }
 
+sub run_fork_detached {
+    my ($fn) = @_;
+
+    pipe(my $rd, my $wr) or die "failed to create pipe: $!\n";
+
+    my $pid = fork();
+    die "fork failed: $!\n" if !defined($pid);
+
+    if (!$pid) {
+       undef $rd;
+       POSIX::setsid();
+
+       eval { $fn->(); };
+       if (my $err = $@) {
+           print {$wr} "ERROR: $err";
+       }
+       POSIX::_exit(1);
+    };
+    undef $wr;
+
+    my $result = do { local $/ = undef; <$rd> };
+    if ($result =~ /^ERROR: (.*)$/) {
+       die "$1\n";
+    }
+
+    if (waitpid($pid, POSIX::WNOHANG) == $pid) {
+       die "failed to spawn process, process exited with status $?\n";
+    }
+}
+
 # NOTE: NFS syscall can't be interrupted, so alarm does
 # not work to provide timeouts.
 # from 'man nfs': "Only SIGKILL can interrupt a pending NFS operation"
-- 
2.48.1



_______________________________________________
pve-devel mailing list
pve-devel@lists.proxmox.com
https://lists.proxmox.com/cgi-bin/mailman/listinfo/pve-devel

Reply via email to