mbrentlinger has asked for the wisdom of the Perl Monks concerning the following question:
#!/usr/bin/perl use Fcntl qw(:DEFAULT :flock); $|=1; if (!defined($child_pid = fork())) { die "cannot fork: $!"; } elsif ($child_pid) { # I'm the parent $file="file.txt"; while ( 1 == 1 ) { $input = <STDIN>; chomp($input); # repeat what was entered st stdin.. then open file.txt, lock +it so others # leave it alone, read it and close it, so others can use it a +gain print "$input\n"; open FH, "<$file"or die "Cannot open $file for read :$!"; flock(FH, LOCK_SH) or die "can't lock filename: $!"; while (<FH>) { print " $_"; } close FH; } } else { # I'm the child $file="file.txt"; while ( 1 == 1 ) { #get some info from a process that can be slow, see if file.tx +t is locked #if not, then open/create the file.txt and write info, and clo +se file. #sleep and repeat @info = `snmpwalk -v 1 -c public $novell_srv .1.3.6.1.4.1.23.2 +.28.3.8.1.2`; sysopen(FH, $file, O_WRONLY | O_CREAT) or die "can't open $fil +e: $!"; flock(FH, LOCK_EX) or die "can't lock $file: $!"; truncate(FH, 0) or die "can't truncate $file: $!"; print FH "@info"; truncate(FH, tell(FH)) or die "can't truncate $file: $!"; close(FH) or die "can't close $file: $!"; sleep 5; }; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: forking and IPC
by Zaxo (Archbishop) on Jun 16, 2005 at 16:23 UTC | |
|
Re: forking and IPC
by Fletch (Bishop) on Jun 16, 2005 at 17:55 UTC |