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