mbrentlinger has asked for the wisdom of the Perl Monks concerning the following question:

I have to do some lookups on some servers (snmp and ldap) based on STDIN input i get from a user. problem is the lookups can possibly take some time and it slows the whole works down.. So here are my thoughts; fork off a child that does the lookups periodically and writes the retuned info back to a file. the parent can then (when it needs to based on STDIN) just rip thru the local file real fast and get what it needs. The problem Im seeing is that the parent and child crash into one another on getting to the file for reads/writes and the whole thing pukes on itself. Any insights on how to do this... or how to do it better would be greatly apprecaited
#!/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

    See flock, which will make processes get to the file in an orderly way. You need to make them exclusive with LOCK_EX.

    After Compline,
    Zaxo

Re: forking and IPC
by Fletch (Bishop) on Jun 16, 2005 at 17:55 UTC

    A more "UNIX-y" way to do it would be to use a pipe between you and the child instead of a file. The parent would use a select loop to determine if there was any pending output from the child waiting to be read.

    --
    We're looking for people in ATL