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

Hello all, I have a cgi script that forks() a process, the script outputs html, but does so twice. looking in the Camel book its says:

Note that unflushed buffers remain unflushed in both processes, which means you may need to set $| on one or more filehandles earlier in the program to avoid duplicate output.

Ok, easy enough. STDOUT is set to 1 ($| = 1) in the main script, what would I set the $| in the forked process? The way I've gotten around this before is to close STDOUT in the forked process, but that gives me a bunch of warnings that I don't want.

anyone hae the quick answer?

 

-justin simoni
!skazat!

Replies are listed 'Best First'.
Re: Duplicate Output with forking
by dws (Chancellor) on Mar 21, 2001 at 03:31 UTC
    Is it possible that you're executing the same code after the fork in both the parent and the child processes?

    Whittle your code down to a small example that demonstrates the problem, and post it. People here love to have code to work from.

      Here's the bare bones, snip:

      #!/usr/bin/perl -w $|++; use CGI qw(:standard); print header(); print h1('howdy!'), hr(); FORK: { if($pid = fork){ }elsif (defined($pid)){ print p('i am a child!') } } print h2("that's all folks");

      This prints

      that's all forks

      before and after it prints 'i am a child!' for me

       

      -justin simoni
      !skazat!

        You're getting the duplicate output because both the parent and the child process are falling through to the same print statement.

        Try having the child exit after it identifies itself. E.g.,

        print p('i am a child!'); exit(0); # don't fall through }