1 # Copyright (C) all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
4 # Pure-Perl implementation of "spawn". This can't take advantage
5 # of vfork, so no speedups under Linux for spawning from large processes.
6 package PublicInbox::SpawnPP;
8 use POSIX qw(dup2 _exit setpgid :signal_h);
10 # Pure Perl implementation for folks that do not use Inline::C
11 sub pi_fork_exec ($$$$$$$) {
12 my ($redir, $f, $cmd, $env, $rlim, $cd, $pgid) = @_;
13 my $old = POSIX::SigSet->new();
14 my $set = POSIX::SigSet->new();
15 $set->fillset or die "sigfillset: $!";
16 sigprocmask(SIG_SETMASK, $set, $old) or die "SIG_SETMASK(set): $!";
18 pipe(my ($r, $w)) or die "pipe: $!";
19 my $pid = fork // die "fork (+exec) @$cmd: $!\n";
24 syswrite($w, my $num = $! + 0);
27 for my $child_fd (0..$#$redir) {
28 my $parent_fd = $redir->[$child_fd];
29 next if $parent_fd == $child_fd;
30 dup2($parent_fd, $child_fd) or
31 die "dup2($parent_fd, $child_fd): $!";
33 if ($pgid >= 0 && !defined(setpgid(0, $pgid))) {
34 die "setpgid(0, $pgid): $!";
36 $SIG{$_} = 'DEFAULT' for grep(!/\A__/, keys %SIG);
38 chdir $cd or die "chdir $cd: $!";
41 my ($r, $soft, $hard) = splice(@$rlim, 0, 3);
42 BSD::Resource::setrlimit($r, $soft, $hard) or
43 die "setrlimit($r=[$soft,$hard]: $!)";
45 $old->delset(POSIX::SIGCHLD) or die "sigdelset CHLD: $!";
46 sigprocmask(SIG_SETMASK, $old) or die "SIG_SETMASK ~CHLD: $!";
49 @$cmd = (which('env'), '-i', @$env, @$cmd);
51 %ENV = map { split(/=/, $_, 2) } @$env;
54 die "exec @$cmd failed: $!";
57 sigprocmask(SIG_SETMASK, $old) or die "SIG_SETMASK(old): $!";
58 if (my $cerrnum = do { local $/, <$r> }) {
60 die "forked child $@: $!";