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";
}
Variables aren't normally shared between processes, if you want to communicate 2 processes you better use pipes or shared memory or any other IPC.
If you really want to share state among multiple processes using an interface that superficially looks like read/write access to variables, you may want to have a look at
IPC::Shareable
.I believe you want to use threads; processes are not threads (although at one point in time Linux threads were implemented using a special type of process which shared memory with its parent).
perldoc -f fork
:See also Bidirectional Communication with Yourself in
perldoc perlipc
.Update: On second thought, do you want something like this?
Output:
You have several options. Threads, sockets, IPC and writing to a file with file locking. Personally I'd recommend threads, they're very easy and safe in Perl, most installations have them compiled and they're fairly performant once a thread has been created.
An interesting alternative is the forks module which emulates threads using a combination of fork() and sockets. I've never used it myself but Elizabeth Mattijsen knows her threads.