How can I make the same variable shared between the forked process? Or do I need to write to a file in the parent then read the value saved to the file in the child once the file exists? $something never appears to get set in this so it just loops in the sleep
my $something = -1;
&doit();
sub doit
{
my $pid = fork();
if ($pid == 0)
{
while ($something == -1)
{
print "sleep 1\n";
sleep 1;
}
&function2();
}
else
{
print "parent start\n";
sleep 2;
$something = 1;
print "parent end: $something\n";
}
}
sub function2 {
print "END\n";
}
perldoc -f fork
:
File descriptors (and sometimes locks on those descriptors) are shared, while everything else is copied.
See also Bidirectional Communication with Yourself in perldoc perlipc
.
Update: On second thought, do you want something like this?
#!/usr/bin/perl
use strict;
use warnings;
my $pid = fork;
die "Cannot fork: $!" unless defined $pid;
if ($pid == 0) {
print "Child start\n";
my $end;
local $SIG{HUP} = sub { $end = 1 };
until ($end) {
print "Sleep 1\n";
sleep 1;
}
function2();
}
else {
print "Parent start\n";
sleep 5;
kill HUP => $pid;
waitpid($pid, 0);
}
sub function2 {
print "END\n";
}
Output:
C:\Temp> w
Parent start
Child start
Sleep 1
Sleep 1
Sleep 1
Sleep 1
Sleep 1
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With