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

Hi all,

I would like to clarify whether using pipe with more than one child process is safe or not. For instance, I would like to fork numerous child process, each having to pass continuous data to its parent process. A simple working version of what I am trying to do is below:

use IO::Socket; use IO::Handle; pipe(READER, WRITER); WRITER->autoflush(1); $| = 1; for ($i=0;$i<10;$i++) { if (!defined($kidpid = fork())) { # fork returned undef, so failed die "cannot fork: $!"; } elsif ($kidpid == 0) { close READER; for (my $p=0;$p<10;$p++) { sleep(1); print WRITER "$$: I am sending mum this message \n"; } close WRITER; exit; } }

Since the child is writing to the parent using  print "data\n" and the parent is reading upto the newline character each time, will the "data" always be correct or is there a possiblity that two child's print data will collide and thus the parent will receive the result of a jumbled effect of the children's message with one read?

For example, I always want the parent to receive

my PID: I am sending mum this message

Many thanks in advance for your help.

Gmong

Replies are listed 'Best First'.
Re: Using pipe with more than one child process
by thospel (Hermit) on Jan 06, 2005 at 05:47 UTC
    Writes to a pipe are atomic as long as they are short enough. This atomic size can be found in your systems header files as the constant PIPE_BUF, and it's defined by posix to be at least 512 bytes (on linux for example it's 4096 bytes). At the perl level the constant can be found in POSIX.pm:
    perl -wle 'use POSIX; print PIPE_BUF'

    So if you make sure that your filehandle to the pipe is autoflushing (so that perl prints become one write), the filehandle isn't unbuffered (normally only a problem with STDERR, in that case make sure your print doesn't consist of many pieces) and your message is short enough (<= 512 bytes), you're safe.

      Thanks heaps thospel.