On Mon, Mar 17, 2025 at 03:11:41PM +0100, Christoph Heiss wrote: > 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.
IIRC there are still outstanding issues with it creating zombie processes because it only does a single fork instead of properly daemonizing with a double-fork. While an alternative to double-forking would be to see if we can add a general child-reaping mechanic to our daemons (either via a proper SIGCLD handler, or a signalfd if AnyEvent supports that?), it is situation dependent on whether the process should be a child process or a "detached" process as the sub below implies - the question there being whether the child should be killed if the parent dies. > > 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