2

我在下面问了以下问题,我找到了一个非常接近的答案,但后来意识到它不起作用。我在 perl 中使用管道。但在我什至通过管道达到我的条件之前,该函数就完成了它的运行。有没有办法在运行时在非常精确的一秒内检查以在 10 个香蕉通过后停止该过程

解析输出并计算字符串出现的次数

你好,我试过这个......但它不起作用......这个过程在我有机会停止它之前就已经完成了。没有任何东西可以实际控制 pid 的流程。我的意思是,在它发现 10 个完成之前,已经有 23 个香蕉越过了。我猜管道流动比实际过程慢

我想要做的就是在已经运行的进程中添加一个延迟。比如:假设我们知道输出会是什么样子: command 1 out command 2 out banana 现在我可以解析香蕉并在此过程中延迟 5 秒。一旦我注入了延迟,我就可以在那个时候运行我的 perl 脚本并及时停止脚本。

为了让我的问题清楚:我写的代码:

my $pid = open my $pipe, '-|', 'commandA | tee banana.foo'
     or die "Error opening pipe from commandA: $!\n";
#  open my $pipe, 'commandA | tee result |'
#    or die "Error opening pipe from commandA: $!\n";
  print "$pid\n";
  my $n = 0;
  while (<$pipe>) {
    $n++ if /banana/;
    last if $n > 0;
    print "pipestring\n";
  }
  kill 'INT', $pid;
  close $pipe;  # kills the command with SIGPIPE if it's not done yet

  if ($n eq 1)  {

  print "commandA printed 'banana'\n";
  }
  else
  {
    print "nothing happened\n";
  }

banana.foo ( actual result )   |  banana.foo (expected result)
one                            |  one
two                            |  two 
three                          |  three 
banana                         |  banana
four
five

所以我不想要最后两个值并希望程序停止。命令A是:

echo one
echo two
echo three
echo banana
echo four
echo five

重要编辑:我想我要做的是创建一个调试器。有人拥有任何开源调试器或其他控制进程的代码。

4

2 回答 2

1

您尝试做的事情永远不会可靠地工作:commandA将数据写入文件的进程与试图杀死它的其他进程之间总是存在竞争。由于两个进程之间有几个缓冲阶段,因此写入进程很可能在被终止之前有机会产生大量额外的输出。

我能想到的避免这种情况的唯一方法是:

  1. 将终止条件检查(打印 10 个“香蕉”后停止)移动到产生输出的程序。这样,你根本不需要杀死它。

  2. 在打印每一行后,让产生输出的程序等待来自其他程序的某种确认。这是可能的,但相当棘手并且可能效率低下。

  3. 而不是使用tee,让控制程序(检查终止条件的程序)将数据写入输出文件,如下所示:

    open my $out, '> banana.foo'
         or die "Error opening banana.foo for writing: $!\n";
    
    my $pid = open my $pipe, 'commandA |'
         or die "Error opening pipe from commandA: $!\n";
    
    my $n = 0;
    while (<$pipe>) {
        print $out $_;
        $n++ if /banana/;
        last if $n > 0;
    }
    kill 'INT', $pid;
    close $pipe;
    
于 2013-07-19T19:33:22.063 回答
-2

我正在编辑这篇文章,因为我显然误解了你的需要。

http://perldoc.perl.org/perlipc.html#Bidirectional-Communication-with-Another-Process

整个页面都有一些关于如何更好地控制子进程等的想法。

于 2013-07-19T19:11:18.813 回答