in reply to Child reading from Parent

I'd probably use a Win32::Semaphore for the signal.

use Win32::Semaphore; my $sem = new Win32::Semaphore(0,1) ... if( my $code_pid = fork() ) { sleep(5); $sem->release(); } elsif( defined $code_pid ) { print "Process executing.."; _spin(); bless $sem, 'do not destroy'; exit 0; ... sub _spin { SPIN: while(! $sem->wait(0)) { ...

The bless $sem, 'do not destroy'; hack is necessary because the fork() did not create a new process, but a new thread under Windows and if you allowed Win32::Semaphore to do proper destroy you'd destroy even the parent's object. (The $sem objects in both threads share the same handle to the semaphore.)

Another option would be to start using "proper" threads. (See perldoc threads. That would allow you to share variables between threads.

HTH, Jenda

Replies are listed 'Best First'.
Re: Re: Child reading from Parent
by icius (Sexton) on Feb 20, 2003 at 00:19 UTC
    I liked the thread idea. How are threads on overhead and processing? The code below seems to work well. However I get the following message when the "Processing Complete" message is printed: "A thread exited while 2 other threads were still running.". Any idea why?
    use threads; use threads::shared; use strict; $|++; my $stream = *STDOUT; my $thingy = [ "\\", "|", "/", "-" ]; my $rate = 0.175; my $step = 0; my $spin_stop : shared; $spin_stop = 0; print "Processing..."; my $thread = threads->create(\&_spin); select(undef,undef,undef, 5); print "\nProcessing Completed\n"; $spin_stop = 1; sub _spin { SPIN: while(1) { my $old_fh = select($stream); local $| = 1; print $stream $$thingy[$step], chr(8) x length($$thingy[$step]); select($old_fh); $step = ( $step+1 > $#$thingy ? 0 : $step+1 ); select(undef,undef,undef, $rate); last SPIN if($spin_stop == 1); } return; }
      OK, I added a $thread->join(); after the $spin_stop = 1; statement which gets rid of the error, but is it good practice?

      If you are running the script under Windows even the fork() uses threads. See perldoc perlfork.

      The big difference is that with fork() you do not get the shared variables and the ->join(). If you use the threads you SHOULD use the ->join(), if you use fork() you should use waitpid(). Though in this case since you do not create many threads the waitpid() is not that important.

      Jenda