Dear Monks.
By the way, is Monks short for Monkeys?
Today's question is ...
I would like to know how the multiprocessing works, when used in Perl function, FORK().
I tried doing this ...
written in pseudo-code
--START--
OPEN FILE TO READ AND WRITE;
IF ($PID = FORK())
{
SLEEP(1);
WRITE 'ALPHA';
SLEEP(5);
WRITE 'BETA';
}
ELSE (DEFINED $PID)
{
SLEEP(3);
READ THE FILE; #Hope to output 'ALPHA'
SLEEP(7);
READ THE FILE; #Hope to output 'ALPHA' and 'BETA'
}
CLOSE THE FREAKING FILE;
--DONE--
What I want to do is,
let the parent write at SLEEP(1) and
let the child read at SLEEP(3)
output : 'ALPHA' and
let the parent write at SLEEP(5) and
let the child read at SLEEP(7)
output : 'ALPHA' 'BETA'.
But of course, thank Perl God, it doesn't work.
But what does work is ...
--START--
IF ($PID = FORK())
{
SLEEP(1);
open file;
WRITE 'ALPHA';
close file;
SLEEP(5);
open file;
WRITE 'BETA';
close file;
}
ELSE (DEFINED $PID)
{
SLEEP(3);
open file;
READ THE FILE;
close file;
SLEEP(7);
open file;
READ THE FILE;
close file;
}
--DONE--
In this program, it opens and closes every time you want to read or write to a file.
So it seems that given one FILE, two processes cannot access the FILE at the same time.
My 'theory' correct?
Any better idea than this continual opening and closing file when reading and writing to a file?
G'day
jsl
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.