libvenus has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I m making a threaded application and inside each thread i m using an external binary to fire a query onto a specific server and port. I then use pipe to read the response of the command. In this process i have noticed that the external binary gets defunct a lot and the application hangs. Below is the code snippet:-

open(HAN,"$allConfig{'pathToClientBinary'} $allConfig{'dmProdH +ost'} $allConfig{'dmProdPort'} $allConfig{'queryMsgType'} \" $duprefo +rmedQuery \"|") || confess "$!"; $prod = <HAN>;

Is there a better and safer way of doing this ?? .. i know i can make sockets but i m unable to format my message in the way the application sever expects and the protocol that talks to the application is not supported in our company specific perl dist.

Any help is greatly appreciated

Thanks

Replies are listed 'Best First'.
Re: Launch External Binary
by moritz (Cardinal) on Oct 09, 2008 at 06:14 UTC
    A safer way is this:
    open my $handle, '-|', $application, @args or confess "can't launch '$application': $!"; while (<$handle>){ # do something here } close $handle or warn "Errors while closing pipe to '$application': $! +";

    The warn message after the close might give you some hints what's wrong.

      As esteemed moritz has suggested, this code is much cleaner, and includes diagnostics for the close. One thing to add; make sure that the last arg in the @arg array is '2>&1'. By default, the pipe operation of open (and shell) only sends stdout. If your application prints any information to stderr, it will be lost.

        Erm, if you call open for a pipe with a list like that it behaves akin to system in that it doesn't run the arguments through a shell so that's not really going to do anything.

        $perl -e 'open( my $x, "-|", "zsh", "-c", q{ctr=1;for i in "$@" ; do p +rint "$ctr: $i"; ctr=$((ctr + 1)); done}, "--", qw(1 2 3 4), q{2>&1} +); print while <$x>; close( $x ); print "\n"' 1: 1 2: 2 3: 3 4: 4 5: 2>&1

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.