gpt4 book ai didi

linux - 安全退出子进程

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:55:48 24 4
gpt4 key购买 nike

我正在尝试学习 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

如何在不退出父进程的情况下退出子进程?

最佳答案

How can I exit the child process without exiting the parent?

父级退出是因为父级到达程序末尾,所以告诉父级做某事,任何事情!例如,

1 while waitpid(-1, 0) > 0;

关于linux - 安全退出子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19362602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com