about summary refs log tree commit homepage
path: root/lib/PublicInbox/SpawnPP.pm
blob: d0df94d0ded0f4cf179a2420a274e13da062be6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Copyright (C) 2016-2018 all contributors <meta@public-inbox.org>
# License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
package PublicInbox::SpawnPP;
use strict;
use warnings;
use POSIX qw(dup2 :signal_h);

# Pure Perl implementation for folks that do not use Inline::C
sub public_inbox_fork_exec ($$$$$$) {
	my ($in, $out, $err, $f, $cmd, $env) = @_;
	my $old = POSIX::SigSet->new();
	my $set = POSIX::SigSet->new();
	$set->fillset or die "fillset failed: $!";
	sigprocmask(SIG_SETMASK, $set, $old) or die "can't block signals: $!";
	my $syserr;
	my $pid = fork;
	unless (defined $pid) { # compat with Inline::C version
		$syserr = $!;
		$pid = -1;
	}
	if ($pid == 0) {
		if ($in != 0) {
			dup2($in, 0) or die "dup2 failed for stdin: $!";
		}
		if ($out != 1) {
			dup2($out, 1) or die "dup2 failed for stdout: $!";
		}
		if ($err != 2) {
			dup2($err, 2) or die "dup2 failed for stderr: $!";
		}

		if ($ENV{MOD_PERL}) {
			exec qw(env -i), @$env, @$cmd;
			die "exec env -i ... $cmd->[0] failed: $!\n";
		} else {
			local %ENV = map { split(/=/, $_, 2) } @$env;
			exec @$cmd;
			die "exec $cmd->[0] failed: $!\n";
		}
	}
	sigprocmask(SIG_SETMASK, $old) or die "can't unblock signals: $!";
	$! = $syserr;
	$pid;
}

1;