package Utilities::ChildProcess;
use strict;

sub send {
    my $prog = shift;

    my $pipe_alive = 1;
    local $SIG{PIPE} = sub { $pipe_alive = 0;};
    if (open CHILD, "| $prog") {
        $pipe_alive && print CHILD @_;
        $pipe_alive && close CHILD;
        if (!$pipe_alive) {
            require LogHandles;
            $LogHandles::ERROR_LOG->print("Broken pipe to '$prog'");
            0;
        } elsif (my $exit_status = $? >> 8) {
            require LogHandles;
            $LogHandles::ERROR_LOG->print("Child process '$prog' returned status $exit_status");
            0;
        } else {
            1;
        }
    } else {
        require LogHandles;
        $LogHandles::ERROR_LOG->print("Unable to open pipe to '$prog': $!");
        0;
    }
}

1;

=head1 NAME

Utilities::ChildProcess - open a pipe to some other process

=head1 SYNOPSIS

 require Utilities::ChildProcess;

 if (Utilities::ChildProcess::send('/usr/bin/blah', 1, 2, 'foo')) {
 # everything OK, keep on truckin'
 } else {
 # something bad happened
 }

=head1 DESCRIPTION

This is a package for opening a pipe to some other process that
interacts with the logging subsystem.

=head2 send

C<send> takes an unlimited number of arguments, with the first
argument being the process to be opened as a pipe.  If the pipe is
successfully opened, the remaining arguments are printed to it, then
the pipe is closed.

The example above is roughly equivalent to:

 open CHILD, "| /usr/bin/blah";
 print CHILD, (1, 2, 'foo');
 close CHILD;

=cut
