简体   繁体   English

在bash脚本中控制可执行文件

[英]Control executable in bash script

First of all, I don't know how to search what I want to do. 首先,我不知道如何搜索我想做的事。

I have one exec that produces outputs in a terminal (Linux). 我有一个exec在终端(Linux)中产生输出。 Let's take a simple C program a.out: 让我们来看一个简单的C程序a.out:

#include <stdio.h>
int main (int argc, char *argv[]) {
int i=0;
float j=0;
for(i=0; i<=10000000;i++)
  {
    j = i*-1e-5;
    printf (" %d 2.0 %f 4.0 5.0\n",i,j);
  }
}

Outputs produced are like : 产生的输出如下:

 0 2.0 -0.000000 4.0 5.0
 1 2.0 -0.000010 4.0 5.0
 2 2.0 -0.000020 4.0 5.0
 3 2.0 -0.000030 4.0 5.0
 ...

Depending on this outputs I want to : 根据此输出,我要:

  1. Launch this exec 启动此执行
  2. "Capture" outputs “捕获”输出
  3. If 3rd column value reach -0.5, stop/kill exec 如果第三列值达到-0.5,则停止/杀死执行程序

How will you do this ? 您将如何做?

For instance, exec is not stopped with this script exec.sh: 例如,exec不会通过以下脚本exec.sh停止:

#/bin/sh
PROG=./a.out
$PROG > output  &
progpid=$!

(tail -fn 0 output & echo $! > tailpid ) | awk -v progpid=$progpid '{
    if($3<=-0.5){
      system("kill "progpid)
      # system( ##update other file )
      system("kill $(<tailpid)")
    }
 }'

Any ideas ? 有任何想法吗 ?

Thanks in advance 提前致谢

I think this sort of construct addresses all of your points: 我认为这种结构可以解决您的所有问题:

programname > output &
progpid=$!
(tail -fn 0 output & echo $! > tailpid ) | awk -v progpid=$progpid '{ 
    if( condition ) { 
        system("kill "progpid)
        system( ##update other file )
        system("kill $(<tailpid)")
    }
}'

We run the program in the background and redirect output to output . 我们在后台运行程序,并将输出重定向到output Then we monitor output as it is updated using the tail -f option, which reads lines from the end of the file as they are added. 然后,我们使用tail -f选项监视output更新时的output ,该选项在添加行时从文件末尾读取行。 Then we pipe this into awk , which can run a system command to kill the program process if condition is met, then run another command to update your parameters in your separate text file, then run another command to kill tail so that it doesn't hang in the background forever ( awk will also exit once tail is killed). 然后,将其通过管道传递给awk ,如果条件满足,该命令可以运行系统命令来终止程序进程,然后运行另一个命令来更新单独文本文件中的参数,然后运行另一个命令来杀死tail ,从而不会tail永远挂在后台(一旦tail被杀死, awk也会退出)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM