【问题标题】:Perl How to exit from child script which does a telnet?Perl 如何从执行 telnet 的子脚本中退出?
【发布时间】:2013-01-21 17:13:58
【问题描述】:

我有一个脚本,它执行几个命令,然后远程登录到机器。现在我需要从另一个 perl 脚本调用这个脚本。

$result = `some_script.pl`;

脚本 some_script.pl 成功执行,但由于脚本在 telnet 提示符处等待,我无法退出主脚本。

我还需要捕获脚本的退出状态,以确保 some_script.pl 成功执行。

我无法修改 some_script.pl。

在 some_script.pl 成功执行后,有什么方法可以让我退出?

【问题讨论】:

  • 为什么要远程登录到一台机器? telnet 到它后它会运行任何东西吗?
  • system('some_script.pl &');

标签: perl telnet exit


【解决方案1】:

我不喜欢您通过“反引号”调用系统来实际执行 perl 脚本的方式。 我建议你实际上 fork(或类似的东西)并以更可控的方式运行程序。

use POSIX ":sys_wait_h";
my $pid = fork();
if($pid) { # on the parent proc, $pid will point to the child
  waitpid($pid); # wait for the child to finish      
} else { # this is the child, where we want to run the telnet
  exec 'some_script.pl'; # this child will now "become" some_script.pl
}

由于我不知道 some_script.pl 的实际工作原理,因此我无法在这里为您提供更多帮助。但是例如,如果您需要做的只是在 some_script.pl 的命令行上打印“quit”,您可以使用 IPC::Open2,就像在 another question 中建议的那样。做类似的事情:

use IPC::Open2;

$pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some_script.pl');
print CHLD_IN "quit\n";
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

您确实需要稍微调整一下,但这个想法应该可以解决您的问题。

【讨论】:

    【解决方案2】:

    试试这个,这个“魔法”关闭标准输入/输出/错误,并可能让您的程序完成。

    $result = `some_script.pl >&- 2>&-

    否则,您可以使用 open2 并期望在程序输出中监视特定字符串(如完成!)并在完成后关闭它。

    http://search.cpan.org/~rgiersig/Expect-1.15/Expect.pod

    问候

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 1970-01-01
      • 2013-12-09
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      相关资源
      最近更新 更多