根据PID判断当前运行的进程为主进程还是子进程,下面的代码在Linux平台可以正确运行。
#!/usr/bin/perl
use 5.006;
use strict;
use warnings;
print "PID = $$/n";
my $child = fork();
die "can not fork:$!" unless defined $child;
if($child > 0)
{
print "parent PID = $$,child PID = $child/n";
}
else
{
my $ppchid = getppid();
print "child pid = $$,parent pid = $ppchid/n";
}
Linux输出结果:
landopen@server01:~$ perl fork.pl
PID = 13322
parent PID = 13322,child PID = 13323
landopen@server01:~$ child pid = 13323,parent pid = 1
Windows报错如下,不支持getppid函数
PID = 1312
The getppid function is unimplemented at D:/Documents and Settings/Administrator/My Documents/fork_child.pl line 18.
The getppid function is unimplemented at D:/Documents and Settings/Administrator/My Documents/fork_child.pl line 18.
本文介绍了一个使用Perl语言编写的简单程序,该程序通过调用fork()函数创建子进程,并利用PID来区分主进程与子进程。此外,还展示了如何在Linux环境下获取父进程ID(ppid),并比较了Windows平台下由于不支持getppid()函数导致的问题。

被折叠的 条评论
为什么被折叠?



