How can I signal a forked child to terminate in Pe

2019-04-09 12:58发布

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";
}

5条回答
爷、活的狠高调
2楼-- · 2019-04-09 13:08

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.

查看更多
Ridiculous、
3楼-- · 2019-04-09 13:12

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.

查看更多
贪生不怕死
4楼-- · 2019-04-09 13:15

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).

查看更多
等我变得足够好
5楼-- · 2019-04-09 13:19

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
查看更多
Root(大扎)
6楼-- · 2019-04-09 13:20

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.

查看更多
登录 后发表回答