【问题标题】:Perl not returning PIDPerl 不返回 PID
【发布时间】:2013-09-01 22:09:15
【问题描述】:

如果我运行命令

nohup ./run > /dev/null 2>&1 & disown

在我的终端中,我得到了类似于 [1] 1234 的内容,我理解为 PID。

但是,当我在 Perl 中运行以下命令时,它会返回关于 disown 未定义或其他内容的错误,但这不是重点。当我删除 disown 时,终端返回相同的内容,但 Perl 什么也不返回。分配给它的变量只是空白。

my $command = `nohup ./run > /dev/null 2>&1 &`;
print("a " . $command); // "a " to check if it's actually printing anything.

输出:

a 

预期输出:

[1] 1234

如何让 Perl 显示命令的 PID,然后我可以用它来解析

@ar  = split(/\s+/, $process);
$pid = $ar[1];

这是我之前的问题中的另一个 Stackoverflow 用户提供的。

【问题讨论】:

    标签: linux perl bash pid


    【解决方案1】:

    [1] 1234 仅由 bash 为交互式 shell 输出(即以 -i 选项开头的 shell)。

    my $command = `sh -ic 'nohup ./run > /dev/null 2>&1 &' 2>&1`;
    die "Can't execute child: $!\n"                if $? < 0;
    die "Child killed by signal ".($? & 0x7F)."\n" if $? & 0x7F;
    die "Child exited with error ".($? >> 8)."\n"  if $? >> 8;
    

    或者更好,

    use IPC::System::Simple qw( capture );
    capture(q{sh -ic 'nohup ./run > /dev/null 2>&1 &' 2>&1});
    

    另一个选项是使用Daemon::Daemonize“守护”。不幸的是,它只通过 pid 文件返回 PID。

    【讨论】:

    • ug,我忘了实际使用使这项工作有效的选项。固定。
    • 不幸的是,两者仍然返回 null
    • 没有 null 这样的东西。详细说明。
    • 然后返回一个空字符串。如果我使用 print 它不会打印任何内容。
    • 如果您在制作 shell 输出 [1] 1234 时遇到问题,您应该首先提及您正在使用的 shell。 (sh --version?) 您还应该为该 shell 标记您的问题,因为您的问题与 Perl 无关。
    【解决方案2】:

    试试这个

      $pin1=`(nohup ./run >/dev/null 2>&1 \& echo \$! )`   
    

    【讨论】:

    • 你能解释一下吗?
    • 我的答案类似于@ikegami : my $command = sh -ic 'nohup ./run &gt; /dev/null 2&gt;&amp;1 &amp;' 2&gt;&amp;1;除了我的代码从 bash shell "echo $!" 获取 pin。
    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 2021-04-26
    相关资源
    最近更新 更多