Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl not able to write to a file handle in child process

Tags:

perl

I need to write some data to a file handle in child. file handle was created in parent before forking. This is because I can read data from the file handle in parent since fork keeps the file handles and locks on them if any, shared between parent and child. This is to share the data in parent and child working both on linux and windows platforms. I was able to to data sharing using IPC::Shareable in linux and this does not work in windows due to unavailability of semaphore.pm in windows [windos does not support semaphore.pm], So for windows I tried Win32::MMF which was crashing my perl compiler.

So with the file handle approach, IO write is not happening in child. Please look in to the below code


use strict;
use warnings;

print "creating file\n"; 
open FH, ">testfile.txt" or die "cant open file: $!\n";
close FH;

my $pid = fork();

if ( $pid == 0 )
{
print "entering in to child and opening file for write\n";
open FH, ">>testfile.txt" or die "cant open file: $!\n";
print FH "dummy data\n";
print FH "dummy data\n";     
print "child sleeping for 5 sec before exiting\n";
sleep 50;
exit;

}
else
{
print "entering the parent process\n";   
open FH, "<testfile.txt" or die "cant open file: $!\n";
 print <FH>;
 print <FH>;


}

like image 670
user2959597 Avatar asked Oct 03 '22 12:10

user2959597


1 Answers

Parent process should wait at least fraction of second to allow child some time for writing.

use strict;
use warnings;

print "creating file\n";
open my $FH, ">", "testfile.txt" or die "cant open file: $!\n";
close $FH;

my $pid = fork();

if ( $pid == 0 ) {
  print "entering in to child and opening file for write\n";
  open my $FH, ">>", "testfile.txt" or die "cant open file: $!\n";
  print $FH "dummy data\n";
  print $FH "dummy data\n";

  # print "child sleeping for 5 sec before exiting\n";
  # sleep 50;
  exit;
}
else {
  sleep 1;
  print "entering the parent process\n";
  open my $FH, "<", "testfile.txt" or die "cant open file: $!\n";
  print while <$FH>;
}

output

creating file
entering in to child and opening file for write
entering the parent process
dummy data
dummy data
like image 150
mpapec Avatar answered Oct 13 '22 10:10

mpapec