Command-Run
view release on metacpan or search on metacpan
lib/Command/Run.pm view on Meta::CPAN
my $want = scalar @$before;
my $have = () = PerlIO::get_layers($fh);
while ($have > $want) {
binmode $fh, ':pop';
my $now = () = PerlIO::get_layers($fh);
last if $now >= $have; # ':pop' made no progress; stop rather than spin
$have = $now;
}
}
sub _execute_in_place {
my $obj = shift;
my $command = shift;
my %opt = @_;
my @command = @$command;
my $stderr_mode = $opt{stderr} // '';
my $raw = $opt{raw};
my $code = shift @command;
my $tmp_stdout = $obj->_tmpfile('NOFORK_STDOUT', raw => $raw);
# Save and redirect STDOUT (always needed)
open my $save_stdout, '>&', \*STDOUT or die "dup STDOUT: $!\n";
my @stdout_layers = PerlIO::get_layers(\*STDOUT);
open STDOUT, '>&', $tmp_stdout or die "redirect STDOUT: $!\n";
binmode STDOUT, $raw ? ':utf8' : ':encoding(utf8)';
# Handle STDERR â only save/redirect when needed
my ($save_stderr, $tmp_stderr);
if ($stderr_mode eq 'redirect') {
open $save_stderr, '>&', \*STDERR or die "dup STDERR: $!\n";
open STDERR, '>&', \*STDOUT or die "redirect STDERR: $!\n";
} elsif ($stderr_mode eq 'capture') {
$tmp_stderr = $obj->_tmpfile('NOFORK_STDERR', raw => $raw);
open $save_stderr, '>&', \*STDERR or die "dup STDERR: $!\n";
open STDERR, '>&', $tmp_stderr or die "redirect STDERR: $!\n";
}
# Handle STDIN â only save/redirect when needed
my $save_stdin;
my @stdin_layers;
if (exists $opt{stdin}) {
my $tmp_stdin = $obj->_tmpfile('NOFORK_STDIN', raw => $raw);
$tmp_stdin->print($opt{stdin});
$tmp_stdin->seek(0, 0) or die "seek: $!\n";
open $save_stdin, '<&', \*STDIN or die "dup STDIN: $!\n";
@stdin_layers = PerlIO::get_layers(\*STDIN);
open STDIN, '<&', $tmp_stdin or die "redirect STDIN: $!\n";
binmode STDIN, $raw ? ':utf8' : ':encoding(utf8)';
} elsif (my $input = $obj->{INPUT}) {
$input->seek(0, 0) or die "seek: $!\n";
open $save_stdin, '<&', \*STDIN or die "dup STDIN: $!\n";
@stdin_layers = PerlIO::get_layers(\*STDIN);
open STDIN, '<&', $input->fileno or die "redirect STDIN: $!\n";
binmode STDIN, $raw ? ':utf8' : ':encoding(utf8)';
}
# Set global state
local $_;
local @ARGV = @command;
my $orig_0;
if (my $name = code_name($code)) {
$orig_0 = $0;
$0 = $name;
}
# Print of the code goes to the handle select()ed by the caller:
# make that STDOUT while it runs
my $prev_select = select(STDOUT);
# Execute
my $result = 0;
eval { $code->(@command) };
if ($@) {
$result = -1;
}
# Flush and restore â only what was redirected.
#
# Pop the layer pushed for raw mode first; the redirect reused the
# handle's PerlIO object, so it would accumulate on every call.
#
# Restore the destination with dup2(), not `open STDOUT, ">&"`:
# re-opening onto a character device (terminal, /dev/null) gives
# the handle a new output side with no layers, and the caller's
# later output would lose its :encoding. dup2() leaves the PerlIO
# object and its layers alone.
# See https://github.com/kaz-utashiro/perl-perlio-leak-bench
STDOUT->flush;
_restore_layers(\*STDOUT, $raw, \@stdout_layers);
defined POSIX::dup2(fileno($save_stdout), fileno(STDOUT))
or die "restore STDOUT: $!\n";
close $save_stdout;
select($prev_select);
if ($save_stderr) {
STDERR->flush;
defined POSIX::dup2(fileno($save_stderr), fileno(STDERR))
or die "restore STDERR: $!\n";
close $save_stderr;
}
if ($save_stdin) {
_restore_layers(\*STDIN, $raw, \@stdin_layers);
open STDIN, '<&', $save_stdin or die "restore STDIN: $!\n";
}
if (defined $orig_0) {
$0 = $orig_0;
}
# Read captured output from tmpfiles
$tmp_stdout->seek(0, 0) or die "seek: $!\n";
my $stdout_data = do { local $/; <$tmp_stdout> };
my $stderr_data = '';
if ($tmp_stderr) {
$tmp_stderr->seek(0, 0) or die "seek: $!\n";
$stderr_data = do { local $/; <$tmp_stderr> };
}
return {
result => $result,
data => $stdout_data,
lib/Command/Run.pm view on Meta::CPAN
->update # (2) STDOUT redirected here
->data;
At step (1), C<require> loads the module and C<use open ':std'>
applies C<:encoding(utf8)> to the B<original> STDOUT. At step (2),
nofork mode redirects STDOUT to a fresh temporary file with
C<:utf8> layer. The callee's encoding setup has already fired on the
original STDOUT and does not affect the redirected one.
This means existing modules like L<App::ansicolumn> and
L<App::ansifold> work unchanged with nofork+raw mode, achieving
significant speedups with zero code changes on the callee side.
For the exceptions, see L</Writing a Callee for Nofork>.
=head2 Writing a Callee for Nofork
In nofork mode, the callee runs in the process of the caller.
Command::Run protects only C<$_>, C<@ARGV>, C<$0> and the standard
file handles. Everything else is shared: global variables, loaded
modules, and the settings of other modules.
A callee should follow these rules.
=over 4
=item Set things up in the function, not at load time.
The module may be loaded by another program, while C<$0> is still the
name of that program. For example, C<ExConfigure> of
L<Getopt::EX::Long> at load time goes to the caller.
=item Do not expect process-wide settings to be fresh.
They may be left by the caller or by an earlier callee. For example,
C<Getopt::Long::Configure> only changes the settings you name, so set
all you need on each call.
=item Do not call C<exit>.
It ends the caller too. Use C<die> or return; C<die> is caught and
the result is -1.
=back
=head2 Caller Protection
Nofork mode executes the code reference in the same process, so care
is needed to prevent the callee from corrupting the caller's state.
The following protections are applied:
=over 4
=item C<local $_;>
Prevents the callee from modifying the caller's C<$_>. This is
critical when the caller aliases C<$_> to important data (e.g.,
greple's C<local *_ = shift> to alias C<$_> to the content buffer).
Without this protection, a callee's C<< while (E<lt>E<gt>) >> loop
would set C<$_> to C<undef> at EOF, destroying the caller's data.
=item C<local @ARGV>
Prevents the callee from modifying the caller's C<@ARGV>.
=item C<$0> save/restore
Prevents the callee from permanently changing the program name.
=back
=head1 COMPARISON WITH SIMILAR MODULES
There are many modules on CPAN for executing external commands.
This module is designed to be simple and lightweight, with minimal
dependencies.
This module was originally developed as L<App::cdif::Command> and
has been used in production as part of the L<App::cdif> distribution
since 2014. It has also been adopted by several unrelated modules,
which motivated its release as an independent distribution.
=over 4
=item L<IPC::Run>
Full-featured module for running processes with support for
pipelines, pseudo-ttys, and timeouts. Very powerful but large
(135KB+) with non-core dependencies (L<IO::Pty>). Overkill for
simple command execution.
=item L<Capture::Tiny>
Excellent for capturing STDOUT/STDERR from Perl code or external
commands. Does not provide stdin input functionality.
=item L<IPC::Run3>
Simpler than L<IPC::Run>, handles stdin/stdout/stderr. Good
alternative but does not support code reference execution.
=item L<Command::Runner>
Modern interface with timeout support and code reference execution.
Has non-core dependencies.
=item L<Proc::Simple>
Simple process management with background execution support.
Focused on process control rather than I/O capture.
=back
B<Command::Run> differs from these modules in several ways:
=over 4
=item * B<Core modules only> - No non-core dependencies
=item * B<Code reference support> - Execute Perl code with $0 and @ARGV setup
=item * B<File descriptor path> - Output accessible via C</dev/fd/N>
( run in 1.614 second using v1.01-cache-2.11-cpan-f5f21f1076c )