如何在不同的脚本中使用 Perl 进行 fork?
我在 Perl 中有一个进程,它使用系统命令创建另一个进程,我将其保留在内存中,并传递一些如下变量:
my $var1 = "Hello";
my $var1 = "World";
system "./another_process.pl $var1 $var2 &";
但系统命令仅返回结果,我需要获取 PID 。我想做一些像fork这样的东西。我应该怎么办?我怎样才能用不同的脚本制作类似 fork 的东西?
提前致谢!
I have a process in Perl that creates another one with the system command, I leave it on memory and I pass some variables like this:
my $var1 = "Hello";
my $var1 = "World";
system "./another_process.pl $var1 $var2 &";
But the system command only returns the result, I need to get the PID. I want to make something like fork. What should I do? How can I make something like fork but in diferent scripts?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Perl 有一个
fork
函数。请参阅
perldoc perlfaq8
- 如何在后台启动进程?Perl has a
fork
function.See
perldoc perlfaq8
- How do I start a process in the background?确实可以使用fork/exec,但我认为简单地使用open的管道形式会容易得多。返回值不仅是您要查找的 pid,您还可以连接到进程的 stdin 或 stdout,具体取决于您打开的方式。例如:
open my $handle, "foo|";
将返回 foo 的 pid 并将您连接到标准输出,这样如果您从 foo 获得一行输出。使用“|foo”代替将允许您写入 foo 的标准输入。
您还可以使用 open2 和 open3 同时执行这两项操作,尽管这有一些主要的注意事项,因为您可能会因 io 缓冲而遇到意外问题。
It's true that you can use fork/exec, but I think it will be much easier to simply use the pipe form of open. Not only is the return value the pid you are looking for, you can be connected to either the stdin or stdout of the process, depending on how you open. For instance:
open my $handle, "foo|";
will return the pid of foo and connect you to the stdout so that if you you get a line of output from foo. Using "|foo" instead will allow you to write to foo's stdin.
You can also use open2 and open3 to do both simultaneously, though that has some major caveats applied as you can run in to unexpected issues due to io buffering.
使用 fork 和 执行。
Use fork and exec.
如果您需要获取 Perl 脚本的 PID,可以使用
$$
变量。您可以将其放入another_process.pl
中,然后让它将 pid 输出到文件中。你能更清楚地了解like fork吗?您始终可以使用 fork exec 组合。If you need to get the PID of a perl script you can use the
$$
variable. You can put it in youranother_process.pl
then have it output the pid to a file. Can you be more clear on like fork? You can always use the fork exec combination.