本文介绍了如何在后台运行 Perl 系统命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/env perl
use warnings; use strict;
use 5.012;
use IPC::System::Simple qw(system);

system( 'xterm', '-geometry', '80x25-5-5', '-bg', 'green', '&' );

say "Hello";
say "World";

我试过这样在后台运行 xterm-command,但它不起作用:

I tried this to run the xterm-command in the background, but it doesn't work:

找不到 shell 的绝对路径:&

让它发挥作用的正确方法是什么?

What would be the right way to make it work?

推荐答案

Perl 的 system函数有两种模式:

Perl's system function has two modes:

  1. 获取单个字符串并将其传递给命令外壳以允许处理特殊字符
  2. 获取字符串列表,执行第一个并将剩余的字符串作为参数传递

在第一种形式中,您必须小心转义可能对 shell 具有特殊含义的字符.第二种形式通常更安全,因为参数直接传递给要执行的程序,而无需涉及 shell.

In the first form you have to be careful to escape characters that might have a special meaning to the shell. The second form is generally safer since arguments are passed directly to the program being exec'd without the shell being involved.

在您的情况下,您似乎混合了两种形式.& 字符如果传递给shell,则仅具有在后台启动此程序"的含义.在您的程序中,与号作为第 5 个参数传递给 xterm 命令.

In your case you seem to be mixing the two forms. The & character only has the meaning of "start this program in the background" if it is passed to the shell. In your program, the ampersand is being passed as the 5th argument to the xterm command.

正如 Jakob Kruse 所说,简单的答案是使用 system 的单字符串形式.如果任何参数来自不受信任的来源,您必须使用引用或转义来确保它们安全.

As Jakob Kruse said the simple answer is to use the single string form of system. If any of the arguments came from an untrusted source you'd have to use quoting or escaping to make them safe.

如果您更喜欢使用多参数形式,那么您需要调用 fork() 然后可能使用 exec() 而不是 system().

If you prefer to use the multi-argument form then you'll need to call fork() and then probably use exec() rather than system().

这篇关于如何在后台运行 Perl 系统命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 16:49
查看更多