我试图学习fork
,这是一个简单的程序:
#!/usr/bin/perl
# PRGNAME.pl by Whom
#
#
use strict;
use warnings;
main(@ARGV);
sub main
{
my @array = qw(1 2 3 4 5 6);
while ( (my $t = pop @array) ) {
if (! (my $pid = fork) ) {
exit if ( $t == 2 );
for(;;){}
}
}
waitpid(-1, 0);
message("This is the $PRGNAME exercise file.");
}
sub message
{
my $m = shift or return;
print("$m\n");
}
sub error
{
my $e = shift || 'unkown error';
print("$0: $e\n");
exit 0;
}
但在我尝试的shell上ps -fu $LOGNAME | grep [f]ork
时,我发现:
i59tib 28361 1 3 16:20:07 pts/34 6:07 /usr/bin/perl ./fork.pl
i59tib 28363 1 3 16:20:07 pts/34 6:07 /usr/bin/perl ./fork.pl
i59tib 28366 1 3 16:20:07 pts/34 6:07 /usr/bin/perl ./fork.pl
i59tib 28364 1 3 16:20:07 pts/34 6:07 /usr/bin/perl ./fork.pl
i59tib 28362 1 3 16:20:07 pts/34 6:08 /usr/bin/perl ./fork.pl
在我评论此行exit if ( $t == 2 );
再次运行ps -fu $LOGNAME | grep [f]ork
,我发现:
i59tib 624 623 1 16:29:11 pts/34 0:04 /usr/bin/perl ./fork.pl
i59tib 629 623 1 16:29:11 pts/34 0:04 /usr/bin/perl ./fork.pl
i59tib 628 623 1 16:29:11 pts/34 0:04 /usr/bin/perl ./fork.pl
i59tib 625 623 1 16:29:11 pts/34 0:04 /usr/bin/perl ./fork.pl
i59tib 627 623 1 16:29:11 pts/34 0:04 /usr/bin/perl ./fork.pl
i59tib 626 623 1 16:29:11 pts/34 0:04 /usr/bin/perl ./fork.pl
i59tib 623 4766 0 16:29:11 pts/34 0:00 /usr/bin/perl ./fork.pl
如何在不退出父级的情况下退出子进程?
答案 0 :(得分:3)
如何在不退出父级的情况下退出子进程?
父母退出是因为父母到达了程序的最后,所以告诉父母做某事,什么都行!例如,
1 while waitpid(-1, 0) > 0;
答案 1 :(得分:0)
如何在不退出父级的情况下退出子进程?
在这里尝试下面的程序孩子在父母之前去世。
#!/usr/bin/perl
print "i am about to fork\n";
my $pid = fork();
if($pid > 0) {
my $i = 0;
while($i<5) {
print "PARENT--I will be keep on running\n";
sleep(5);
$i++;
}
print "PARENT-- I m about to dead\n";
} else {
$i = 0;
while($i <3) {
print "CHILD-- I will be dead before than parent\n";
#exit(0); you can put exit like this also.
sleep(2);
$i++;
}
print "CHILD-- I m about to dead\n";
}
以下是示例输出。
i am about to fork
PARENT--I will be keep on running
CHILD-- I will be dead before than parent
CHILD-- I will be dead before than parent
CHILD-- I will be dead before than parent
PARENT--I will be keep on running
CHILD-- I m about to dead
PARENT--I will be keep on running
PARENT--I will be keep on running
PARENT--I will be keep on running
PARENT-- I m about to dead
您也可以使用任何支持的信号。您可以获得不同的信号列表here。您也可以在循环中使用相同的示例代码,但请确保将有一个超级父级,其他将是他们的孩子。
请运行此程序以了解更多相关信息。无论您是否使用退出,总是超级父母将退出。
#!/usr/bin/perl
print "i $$ am about to fork\n";
my @children_pids;
my $n = 3;
for my $i ( 0..($n-1) ) {
my $pid = fork();
if($pid > 0) {
print "i m $$ child of".getppid()."\n";
push @children_pids, $pid;
} else {
print "I $$ is about to dead. I am child of".getppid()."\n";
exit();
}
}
waitpid $_, 0 for @children_pids;
print "$$ is finished\n";
我的上述程序系统的典型输出如下。
i 3919 am about to fork
i m 3919 child of3092
I 3920 is about to dead. I am child of3919
i m 3919 child of3092
i m 3919 child of3092
I 3921 is about to dead. I am child of3919
I 3922 is about to dead. I am child of3919
3919 is finished
父母将等待所有孩子退出;然后只有退出。