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

Dear Monks,

I'm struggling with autoflush in a Perl program that needs to catch the results of tcpdump running as root. The codes are as shown below. Though I set autoflush of the file handle, TCPDump, to true, it doens't seem working. Really appreciate if any monks can shred some light on this. Many thanks.

#!/usr/bin/perl -w use strict; use warnings; use IO::Handle; my ($Interface, $Multicast, $Port) = ('eth3', '226.1.109.109', '12345' +); open (TCPDump,"sudo /usr/sbin/tcpdump -i $Interface host $Multicast 2> +/dev/null |") || die "Can't open tcpdump : $!"; TCPDump->autoflush(1); while (<TCPDump>) { print "$_"; }

Replies are listed 'Best First'.
Re: Autoflush fails
by Anonymous Monk on May 31, 2012 at 03:39 UTC
    autoflush means flush after write (print), but you do not print to TCPDump

      Thanks for your reply. What I want is to flush the results of "sudo /usr/sbin/tcpdump -i $Interface host $Multicast 2>/dev/null |" to TCPDump. I tried "$| = 1" but it didn't work either. Any suggestion I can make the while loop to print the traffic at once? I tried the sudo command in a bash shell and I can see the results right away. However, the output of the sudo tcpdump feeding to TCPDump is batched in my Perl program. This causes the rest of the codes(removed here) to fail.

        Autoflush is something you do in your program, to control the output of your program , not something you can do to other programs

        Other than changing your invocation (sudo ... ) there is nothing you can do

        You say sudo ... works from bash, but does  sudo ... |perl -pe 1 work the same?

Re: Autoflush fails
by NetWallah (Canon) on May 31, 2012 at 05:23 UTC
    Try the -l (Lower-case l, as in lazy) option of tcpdump.

    According to the docs,

    -l Make stdout line buffered. Useful if you want to see the data while capturing it.

    The -U -w - options in tcpdump make the output unbuffered.

    Web search shows this article.
    and commandlinefu shows a trick of chaining 2 tcpdumps to achieve this.

                 I hope life isn't a big joke, because I don't get it.
                       -SNL

      thanks. problem resolved by -l :-)

A reply falls below the community's threshold of quality. You may see it by logging in.