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

Greetings,
I'm trying to understand why I'm getting malformed headers from my cgi-bin program written under perl, but not the equivalent under csh. If I system() to a command that writes to stdout, apache returns a "malformed header from script" error. If I do the same thing command that doesn't, everything works fine.
So:
printf("Content-type: text/html\n\n"); system("touch /usr/tmp/bogus");
works, but:
printf("Content-type: text/html\n\n"); system("echo hello");
doesnt. If I do the same thing under csh or c, it works fine. In fact, just using csh, the server acts as if I have non-parsed-headers and prints the output of my external program (which takes about 1sec to run, and gets called 20 or so times) sequentially each time it is called, which gives my users a nice status update. I've also tried turning autoflush on stdout for the script:
$old_fh = select(OUTPUT_HANDLE); $| = 1; select($old_fh);
but that doesn't seem to do it either.

Thanks for any insights!
--david

Replies are listed 'Best First'.
Re: system() and malformed headers
by Anonymous Monk on Jul 07, 2001 at 07:27 UTC
    I have to be going, but here's a few things I thought:

    Turn off buffering:

    $| = 1;
    Try backticks:
    my $output = `touch /usr/tmp/bogus`;
    Redirect system()'s stdout and stderr to /dev/null:
    system("touch /usr/tmp/bogus > /dev/null 2>&1");
    Good luck.
      Hi there, Turning off buffering with $|=1 didn't work, but the backticks did the trick.
      thanks!
      --david
Re: system() and malformed headers
by Anonymous Monk on Jul 07, 2001 at 08:11 UTC
    You must write a header before you write to stderr, your printf statement gets buffered by libc and isn't actually written to stdout until after the system call and because stderr is not buffered it gets written first. When you execute the program from the shell it works fine because stdout on a tty is line buffered. If you redirect the output from the command line to a file (/path/to/program > filename 2>&1) you will probably see the stderr before the stdout.
Re: system() and malformed headers
by John M. Dlugosz (Monsignor) on Jul 08, 2001 at 00:20 UTC
    My guess would be, assuming that "echo hello" is indeed printing to standard output and prints nothing to stderr, that the output in Perl is being buffered by library IO code that the OS doesn't see. OHOH, that would be a common thing and system() would be programmed to flush first...hmm.

    Anyway, what is OUTPUT_HANDLE in your last code block? Just do $|=1; by itself at the top of the script, to apply this to STDOUT.