]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SpawnPP.pm
Merge commit 'mem'
[public-inbox.git] / lib / PublicInbox / SpawnPP.pm
1 # Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
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;
7 use strict;
8 use warnings;
9 use POSIX qw(dup2 :signal_h);
10
11 # Pure Perl implementation for folks that do not use Inline::C
12 sub public_inbox_fork_exec ($$$$$$) {
13         my ($in, $out, $err, $f, $cmd, $env) = @_;
14         my $old = POSIX::SigSet->new();
15         my $set = POSIX::SigSet->new();
16         $set->fillset or die "fillset failed: $!";
17         sigprocmask(SIG_SETMASK, $set, $old) or die "can't block signals: $!";
18         my $syserr;
19         my $pid = fork;
20         unless (defined $pid) { # compat with Inline::C version
21                 $syserr = $!;
22                 $pid = -1;
23         }
24         if ($pid == 0) {
25                 if ($in != 0) {
26                         dup2($in, 0) or die "dup2 failed for stdin: $!";
27                 }
28                 if ($out != 1) {
29                         dup2($out, 1) or die "dup2 failed for stdout: $!";
30                 }
31                 if ($err != 2) {
32                         dup2($err, 2) or die "dup2 failed for stderr: $!";
33                 }
34
35                 if ($ENV{MOD_PERL}) {
36                         exec qw(env -i), @$env, @$cmd;
37                         die "exec env -i ... $cmd->[0] failed: $!\n";
38                 } else {
39                         local %ENV = map { split(/=/, $_, 2) } @$env;
40                         exec @$cmd;
41                         die "exec $cmd->[0] failed: $!\n";
42                 }
43         }
44         sigprocmask(SIG_SETMASK, $old) or die "can't unblock signals: $!";
45         $! = $syserr;
46         $pid;
47 }
48
49 1;