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::Spawn;
7 our @EXPORT_OK = qw/which spawn/;
9 my $vfork_spawn = <<'VFORK_SPAWN';
10 #include <sys/types.h>
15 #define AV_ALLOCA(av, max) alloca((max = (av_len((av)) + 1)) * sizeof(char *))
17 static void av2c_copy(char **dst, AV *src, I32 max)
21 for (i = 0; i < max; i++) {
22 SV **sv = av_fetch(src, i, 0);
23 dst[i] = sv ? SvPV_nolen(*sv) : 0;
28 static void *deconst(const char *s)
30 union { const char *in; void *out; } u;
35 /* needs to be safe inside a vfork'ed process */
36 static void xerr(const char *msg)
39 const char *err = strerror(errno); /* should be safe in practice */
41 iov[0].iov_base = deconst(msg);
42 iov[0].iov_len = strlen(msg);
43 iov[1].iov_base = deconst(err);
44 iov[1].iov_len = strlen(err);
45 iov[2].iov_base = deconst("\n");
51 #define REDIR(var,fd) do { \
52 if (var != fd && dup2(var, fd) < 0) \
53 xerr("error redirecting std"#var ": "); \
57 * unstable internal API. This was easy to implement but does not
58 * support arbitrary redirects. It'll be updated depending on
59 * whatever we'll need in the future.
60 * Be sure to update PublicInbox::SpawnPP if this changes
62 int public_inbox_fork_exec(int in, int out, int err,
63 SV *file, SV *cmdref, SV *envref)
65 AV *cmd = (AV *)SvRV(cmdref);
66 AV *env = (AV *)SvRV(envref);
67 const char *filename = SvPV_nolen(file);
72 argv = AV_ALLOCA(cmd, max);
73 av2c_copy(argv, cmd, max);
75 envp = AV_ALLOCA(env, max);
76 av2c_copy(envp, env, max);
83 execve(filename, argv, envp);
84 xerr("execve failed");
91 my $inline_dir = $ENV{PERL_INLINE_DIRECTORY};
92 $vfork_spawn = undef unless defined $inline_dir && -d $inline_dir && -w _;
93 if (defined $vfork_spawn) {
94 # Inline 0.64 or later has locking in multi-process env,
95 # but we support 0.5 on Debian wheezy
98 my $f = "$inline_dir/.public-inbox.lock";
99 open my $fh, '>', $f or die "failed to open $f: $!\n";
100 flock($fh, LOCK_EX) or die "LOCK_EX failed on $f: $!\n";
101 eval 'use Inline C => $vfork_spawn';
102 flock($fh, LOCK_UN) or die "LOCK_UN failed on $f: $!\n";
105 warn "Inline::C failed for vfork: $@\n";
106 $vfork_spawn = undef;
110 unless (defined $vfork_spawn) {
111 require PublicInbox::SpawnPP;
113 *public_inbox_fork_exec = *PublicInbox::SpawnPP::public_inbox_fork_exec
118 foreach my $p (split(':', $ENV{PATH})) {
126 my ($cmd, $env, $opts) = @_;
127 my $f = which($cmd->[0]);
128 defined $f or die "$cmd->[0]: command not found\n";
132 my %env = $opts->{-env} ? () : %ENV;
134 foreach my $k (keys %$env) {
143 while (my ($k, $v) = each %env) {
146 my $in = $opts->{0} || 0;
147 my $out = $opts->{1} || 1;
148 my $err = $opts->{2} || 2;
149 public_inbox_fork_exec($in, $out, $err, $f, $cmd, \@env);