in reply to Concurrency : FORK and knife
In Perl, I would recommend using IPC::SysV. It seems better suited than just the Perl primitives. Here's a quick little Perl blurb (warning: untested).$SEM = CREATE SEMAPHORE; IF ($PID == FORK()) { wait($SEM); # grab the semaphore open file; WRITE 'ALPHA'; close file; signal($SEM); # signal semaphore wait($SEM); # wait for signal from child open file; WRITE 'BETA'; close file; signal($SEM); # signal semaphore } ELSE IF(DEFINED $PID) { SLEEP(3); # make sure parent grabs semaphore wait($SEM); # wait for signal from parent open file; READ THE FILE; close file; signal($SEM); # done with file ops, signal semaphore wait($SEM); # wait for signal from parent that it is done writing +to file open file; READ THE FILE; close file; signal($SEM); }
Of course, that, again, might be an overkill. You could probably accomplish it with some extra file foo or so.use IPC::SysV qw(IPC_PRIVATE S_IRWXU IPC_CREAT); use IPC::Semaphore; my $sem = new IPC::Semaphore(IPC_PRIVATE, 1, S_IRWXU | IPC_CREAT); $sem->setall( (0) x 10); my $semid = $sem->getVal($sem); if(my $pid = fork()) { $sem->op($semid, -1, IPC_NOWAIT); #get the semaphore open(FILE, ">/myFile.txt") or die "error: $!\n"; print FILE "Hello, my name is Perl.\n"; close FILE; $sem->op($semid, 1, IPC_NOWAIT); # signal semaphore $sem->op($semid, -1, IPC_NOWAIT); #wait on semaphore open(FILE, ">/myFile.txt") or die "error: $!\n"; print FILE "Hello, again, my child.\n"; close FILE; $sem->op($semid, 1, IPC_NOWAIT); # signal semaphore } elsif(defined $pid) { sleep(3); $sem->op($semid, -1, IPC_NOWAIT); #wait on semaphore open(FILE, "/myFile.txt") or die "error: $!\n"; print while(<FILE>); close FILE; $sem->op($semid, 1, IPC_NOWAIT); # signal semaphore $sem->op($semid, -1, IPC_NOWAIT); #wait on semaphore open(FILE, "/myFile.txt") or die "error: $!\n"; print while(<FILE>); close FILE; $sem->op($semid, 1, IPC_NOWAIT); exit(0); #exit child } $sem->remove;
|
|---|