Perl fork()
Forking in perl is a nice thing to do, and for some it’s a hard thing to understand. It can be pretty easy to get lost especially since there are 100 ways to the same thing. I’m going to attempt to explain a little bit of the inner workings of fork() in Perl.
First you have to understand what fork() returns. When you do:
my $pid = fork();
If it is the parent, $pid will be assigned the PID of the child.
If it is the child, $pid will be assigned 0.
If it cannot fork anymore because of no resources, $pid will be undefined.
To help show how a fork() program works, I’m going to use this sample script:
#!/usr/bin/perl
my $pid = fork();
if (not defined $pid) {
print “resources not avilable.\n”;
} elsif ($pid == 0) {
print “IM THE CHILD\n”;
sleep 5;
print “IM THE CHILD2\n”;
exit(0);
} else {
print “IM THE PARENT\n”;
waitpid($pid,0);
}
print “HIYA\n”;
If run, you will see this:
$ ./f.pl
IM THE CHILD
IM THE PARENT
- sleep for 5 seconds -
IM THE CHILD2
HIYA
$ ps -ef | grep fork1.pl
derek 6440 2888 0 15:45 pts/2 00:00:00 /usr/bin/perl ./fork1.pl
derek 6441 6440 0 15:45 pts/2 00:00:00 /usr/bin/perl ./fork1.pl
This is a pretty simple script and self explanatory. It starts out with the fork and then checks the value of $pid through the if statements and executes the block of code accordingly. What you really have to understand is that when fork() is called, you now have 2 programs that are the same. So in this example, when we do my $pid = fork(); you now have 2 processes running. Each process will run the code. It looks like $pid is only being assigned one value here but it is actually being assigned two or even three values (undefined if necessary). When the parent runs checking through the if statements, it will catch on the last else statement here because $pid is assigned PID of the child. When the child runs through this block of code, it will catch on the if ($pid == 0) because the $pid is assigned 0 for a child. The waitpid() call just waits for the child to exit. If you do not do this it will become a zombie (defunct) process, which means it has become detached from it’s parent.
So here is exactly what happens when you run this:
- The program forks, you now have 2 processes, one is the child, one is the parent.
- if (not defined $pid) gets run on both processes, and die’s if resources aren’t available.
- elsif ($pid == 0) gets run on both processes, if its the child, print “IM THE CHILD”, sleep for 5 seconds and then print “IM THE CHILD 2″ and exit(0);
- While the above statement is running on the child, the parent is going along with the else {} block of code and prints “IM THE PARENT” and then waits for the child to exit.
NOTE: The exit(0) in the child block is very important.. you need the child to exit its process when it is done, so it will no longer exist.
fork
首先说说 fork 函数。这个函数用来创建一个进程,不过创建方法有些不太好理解。 先看下面的程序 fork-test.pl。我是用perl写的,不过相同的功能也可以用 C 来完成。
#!/usr/bin/perl#------------------------------------# fork-test.plprint "Program started, pid=$$.\n";if ($child_pid = fork()) { print "I'm parent, my pid=$$, child's pid=$child_pid.\n";} else { print "I'm child, pid=$$.\n";}
运行之后显示下面的结果。
Program started, pid=8934.I'm child, pid=8935.I'm parent, my pid=8934, child's pid=8935.
为什么 I'm child 和 I'm parent 都会被显示?这是因为 fork 调用时, 当前的进程会从 fork 的位置一分为二,fork 对两个进程的返回值不同。 在父进程中 fork 返回子进程(即另一个进程)的进程id,而在子进程中 fork 返回 0。 上例的执行过程如下图。
上例中执行到 Program started 时,只有一个进程 8934,而执行到 fork 时, 进程分为两个,父进程为 8934,子进程为 8935。接下来父进程执行 if 分支, 输入“I'm parent..”,而子进程执行 else 分支,输出 “I'm child”。
SIGCHLD信号和僵尸进程
首先说说什么是僵尸进程(zombie process)。我们知道 Linux 使用进程表来管理进程, 每个进程都在进程表中占据一个位置。当我们用 fork 生成一个子进程, 然后该子进程退出时,系统不会自动回收该子进程所占位置。 此时虽然进程表中有这个子进程的信息,但实际上该子进程早已结束, 于是这个进程就成了“僵尸进程”。
僵尸进程虽然不占用系统资源,但是它会浪费进程表的位置。如果僵尸进程太多, 有可能会导致不能创建新进程。下面的例子 zombie-test.pl 演示了如何创建僵尸进程:
#!/usr/bin/perl#------------------------------------# zombie-test.plsub child { print "I'm child, pid=$$.\n";}while (1) { if (fork() == 0) { &child; # 如果当前进程是子进程,则执行 child 函数 exit; # 并退出 } else { sleep 5; # 如果是父进程,则睡眠 5 秒 }}
该程序每隔 5 秒创建一个子进程,子进程输出一行文字后退出。 执行该程序片刻之后,从其他终端用 ps -ef 命令可以看到进程状态。 标有 <defunct> 的就是僵尸进程。
charlee 11687 10870 0 02:01 pts/1 00:00:00 /usr/bin/perl perl/zombie-test.plcharlee 11688 11687 0 02:01 pts/1 00:00:00 [zombie-test.pl] <defunct>charlee 11691 11687 0 02:01 pts/1 00:00:00 [zombie-test.pl] <defunct>charlee 11695 11687 0 02:01 pts/1 00:00:00 [zombie-test.pl] <defunct>
如何避免僵尸进程?当子进程结束时,系统会向父进程发送 SIGCHLD 信号。 父进程只要在处理这个信号时回收子进程占用的资源即可。
利用 waitpid 回收僵尸进程
一个方法就是在父进程中利用 waitpid 函数。该函数回收指定进程的资源, 并返回已结束进程的进程id。若指定进程不存在,则返回 -1。 我们可以通过调用 waitpid(-1, WNOHANG) 来回收所有子进程。 Perl 提供了全局变量 %SIG,只要设置该变量即可安装信号处理程序。 下面的 waitpid_test1.pl 演示了使用方法。完整的代码可以从本文的附件中下载。
use POSIX ":sys_wait_h";$SIG{CHLD} = \&REAPER;sub REAPER { my $pid; while (($pid = waitpid(-1, WNOHANG)) > 0) { # 进行一些处理 }}
执行这个程序并用 ps -ef 查看进程,可以发现僵尸进程不再出现了。
不过上面这个程序有个问题。Linux的信号是不能排队的, 如果信号到达进程时进程不能接收该信号,这个信号就会丢失。 REAPER 中包含比较耗时的 while 循环,如果在 REAPER 执行过程中 发生 SIGCHLD 信号,这个信号就会丢失。为了避免这种情况, 我们可以尽量减少信号处理的执行时间。参考下面的 waitpid_test2.pl。
our $zombies = 0; # 记录系统中僵尸进程的数目$SIG{CHLD} = sub { $zombies++ }; # 信号处理程序中仅仅统计僵尸进程数目# 主程序while (1) { if (fork() == 0) { &child; # 如果当前进程是子进程,则执行 child 函数 exit; # 并退出 } else { &REAPER if $zombies; sleep 5; # 如果是父进程,则睡眠 5 秒 }}
实际上,waitpid_test2.pl 并不能及时回收结束的子进程—— 由于 REAPER 在主程序中执行,如果子进程结束时主程序尚未执行到 REAPER 一行, 那么系统中可能会出现相当数量的僵尸进程,直到主程序执行 REAPER 为止。 不过一般情况下这种方法已经足够用了。
忽略 SIGCHLD 回收僵尸进程
另一个比较简单的方法就是直接忽略 SIGCHLD 信号,系统会自动回收结束的子进程。 参见下面的 ignore_sigchld_test.pl。
$SIG{CHLD} = 'IGNORE'; # 忽略 SIGCHLD 信号
与前面的 waitpid 方法相比,此方法虽然方便, 但缺点就是父进程无法在子进程结束时做些处理。 可根据实际需要选择最合适的方法。
本文源代码下载 perl-source.zip
################################################
#!/usr/bin/perl
#------------------------------------
# ignore_sigchld_test.pl
$SIG{CHLD} = 'IGNORE'; # 忽略 SIGCHLD 信号
sub child {
print "I'm child, pid=$$.\n";
}
while (1) {
if (fork() == 0) {
&child; # 如果当前进程是子进程,则执行 child 函数
exit; # 并退出
} else {
sleep 5; # 如果是父进程,则睡眠 5 秒
}
}################################################
分享到:
相关推荐
fork一个进程,fork()函数fork()函数通过系统调用创建一个与原来进程几乎完全相同的进程,这个新产生的进程称为子进程。一个进程调用fork()函数后,系统先给新的进程...
创建新进程:fork函数:fork函数干什么? fork函数与vfork函数的区别在哪里?为何在一个fork的子进程分支中使用_exit函数而不使用exit函数?
linux 进程 线程 fork 的深入思考 一道面试题的思考
该文档编写的主要目的是通过fork创建多个子进程的方法。
fork()编程fork()编程fork()编程fork()编程fork()编程fork()编程fork()编程
linux 多进程编程 forklinux 多进程编程 forklinux 多进程编程 forklinux 多进程编程 forklinux 多进程编程 forklinux 多进程编程 forklinux 多进程编程 forklinux 多进程编程 forklinux 多进程编程 forklinux 多...
里面是三个实验,分别是fork创建子进程,各个进程之间的关系,并发还是同步,以及子进程复制父进程代码的说明
fork后子进程从哪里开始执行
fork3()编程fork3()编程fork3()编程fork3()编程fork3()编程fork3()编程fork3()编程
本文档内容是我自己写的一个关于fork函数新建进程并对调用流程进行分析的文档。 运行环境是win7安装vmware虚拟机里的linux系统,直接gcc编译得到的执行结果。 看完次文档后即可对fork有一个比较系统的认识。
fork1() 编程fork1() 编程fork1() 编程fork1() 编程fork1() 编程fork1() 编程fork1() 编程
使用系统调用fork()创建两个子进程,再用系统调用signal()让父进程捕捉键盘上的中断信号(即按DEL键);当捕捉到中断信号后,父进程用系统调用Kill()向两个子进程发出信号,子进程捕捉到信号后分别输出下列信息后终止: ...
该事例程序属多进程调用小程序,采用了系统调用函数fork()进行子进程的调用。在该文档中介绍了fork()调用的相关细节及注意点以及父子进程段的关系。并将程序运行后输出到屏幕结果与输出重定向到文件后的结果进行比较...
这是大二操作系统的实验课程,控制进程间的通信,附含实验报告。此实验的代码及思想方法与之前的一般方法完全有所不同.
基于C语言实现的双工TCP通信,TCP通信fork进程
进程创建函数fork()的基础实验,具体看博客http://blog.csdn.net/mybelief321/article/details/9046955
perl catalyst translated by 小生菜菜 博文链接:https://kotime42.iteye.com/blog/147360
编写一段程序,使用系统调用fork()创建两个子进程。当此程序运行时, 在系统中有一个父进程和两个子进程活动。 让每一个进程在屏幕上显示一个字符:父进程显示“A”; 子进程分别显示字符“b”和“c”。试观察记录...
系统调用fork( ), exec系列函数,exit( ), wait( )的功能和实现过程 使用系统调用fork( )创建两个子进程。当此程序运行时,在系统中有一个父进程和两个子进程活动。让每一个进程在屏幕上显示一个字符:父进程显示...
fork 是一个管理git代码的一个可视化客户端