Hi,

I have a parent process that forks 10 children. I would like each child to get a copy of a 'master' socket, do some work, and then write to master socket - atomically.

Unfortunately, 1 out 10 times I run the script, the results are garbled - my current theory is the children are not doing atomic writes to the socket.

I've tried:

* set autoflush to on ($| = 1) * using print and syswrite (both are garbled) * flocking the socket filehandle in the child processes
Flocking the socket filehandle does not grant an exclusive lock.

The situation it similar to multiple web servers appending to a log file. I've read that one solution is to set the filehandle to '>> append' mode and use syswrite - but I'm not sure if this is going to work with sockets.

I'm also thinking about trying to 'lock' the socket by using a filesystem lock on a PID file - but this seems a bit kludgy.

And ideas?

Regards,

Nige

p.s. prior to forking the children I copy the socket to STDOUT with: *STDOUT = *{$c}; # $c = socket

Edit by tye


In reply to forking() flocking() on sockets by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.