本文首发于: https://blog.frytea.com
最近阅读 PVE 源码发现一处源码这样使用了 fork()
方法:
$spid = fork();
if (!defined ($spid)) {
die "can't put server into background - fork failed";
} elsif ($spid) { # parent
exit (0);
}
自己写示例发现这种方法可以使程序进入后台执行状态,大概原理是 fork 子进程,退出主进程,使得程序被 1 号父进程接管,在终端表现则是进入了后台执行状态。
以下是实例代码:
#!/usr/bin/perl
sub mainThread() {
print "---------- Main Thread! ------------\n";
$spid = fork();
if (!defined ($spid)) {
die "can't put server into background - fork failed";
} elsif ($spid) { # parent
exit (0);
}
for(;;)
{
print "Hello, world in main thread!\n";
sleep 1;
}
}
mainThread();
看下进程状态:
退出程序则是指定 PID 即可:
$ kill -9 3300
参考文献
- functions / exit (source, CPAN)
- functions / fork (source, CPAN)
- 在linux中如何关闭或者停用守护进程
- 关于perl中Exit的函数使用
- Linux中的程序和进程,PID和PPID
---------------------
Author: Frytea
Title: Perl 程序后台执行示例
Link: https://blog.frytea.com/archives/563/
Copyright: This work by TL-Song is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.