How can I pass a forked child to Perl?

How can I make the same variable shared between a forked process? Or do I need to write to the file in the parent and then read the value stored in the file in the child file after the file exists? $ something never appears in this, so it just winds around in a dream

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"; } 
+4
source share
5 answers

perldoc -f fork :

File descriptors (and sometimes locks on these descriptors) are shared, and everything else is copied.

See also Bidirectional communication with you at perldoc perlipc .

Update: On the other hand, 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 
+9
source

Variables are usually not shared between processes, if you want to communicate with two processes, you are better off using pipes or shared memory or any other IPC.

+6
source

If you really want to split the state between several processes using an interface that looks like read / write access to variables, you might want to take a look at IPC::Shareable .

+1
source

I believe you want to use streams; processes are not threads (although at one point in time, Linux threads were implemented using a special type of process that shares memory with its parent).

0
source

You have several options. Themes , sockets , IPC and write to a file with file locking. Personally, I would recommend themes, they are very easy and safe in Perl, most installations are compiled, and they are quite effective after creating the stream.

An interesting alternative is the forks module, which emulates threads using a combination of fork () and sockets. I never used it myself, but Elizabeth Mattisen knows her own topics.

0
source

All Articles