我如何检查是否一个GNU awk的协进程是开放的,或者强迫它不写它打开? [英] How can I check if a GNU awk coprocess is open, or force it to open without writing to it?

查看:89
本文介绍了我如何检查是否一个GNU awk的协进程是开放的,或者强迫它不写它打开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用一个协徒劳无功程序。但是,有时我没有任何数据写入到协进程,并在等待协进程的输出我的原始脚本挂起。

在code下面从STDIN读取,每一行写入一个猫的程序,运行在一个协。然后,它读取协同进程输出回,并将其写入到标准输出。如果我们改变if条件为1 == 0,没有东西写到协进程,程序挂在while循环。

从<一个href=\"http://www.gnu.org/software/gawk/manual/html_node/Two_002dway-I_002fO.html#Two_002dway-I_002fO\"相对=nofollow>手动,似乎协进程和双向通信信道才开始首次出现与一个IO操作|&安培;运营商。或许我们可以实际上不写任何东西(例如写一个空字符串)开始的事情?或者是有没有办法来检查,如果协同进程不断开始了吗?

 #!的/ usr /斌/的awk -f
开始 {
    CMD =猫
##打印,|&安培; CMD
}{
    如果(1 == 1){
       打印|&安培; CMD
    }
}结束 {
    关闭(CMD为)
    而((CMD |&放大器;函数getline线)大于0){
       打印线
    }
    关闭(CMD)
}


解决方案

大问题,一为那个!

刚刚测试关闭返回code(CMD,以) - 这将是零,如果管道被打开,-1(或其他值),否则。例如:

 如果(接近(CMD为)== 0){
   而((CMD |&放大器;函数getline线)大于0){
      打印线
   }
   关闭(CMD)
}

I have a gawk program that uses a coprocess. However, sometimes I don't have any data to write to the coprocess, and my original script hangs while waiting for the output of the coprocess.

The code below reads from STDIN, writes each line to a "cat" program, running as a coprocess. Then it reads the coprocess output back in and writes it to STDOUT. If we change the if condition to be 1==0, nothing gets written to the coprocess, and the program hangs at the while loop.

From the manual, it seems that the coprocess and the two-way communication channels are only started the first time there is an IO operation with the |& operator. Perhaps we can start things without actually writing anything (e.g. writing an empty string)? Or is there a way to check if the coprocess ever started?

#!/usr/bin/awk -f
BEGIN {
    cmd = "cat"
##  print "" |& cmd
}

{
    if (1 == 1) {
       print |& cmd
    } 
}

END {
    close (cmd, "to")
    while ((cmd |& getline line)>0) {
       print line
    }
    close(cmd)
}

解决方案

Great question, +1 for that!

Just test the return code of the close(cmd, "to") - it will be zero if the pipe was open, -1 (or some other value) otherwise. e.g.:

if (close(cmd, "to") == 0) {
   while ((cmd |& getline line)>0) {
      print line
   }
   close(cmd)
}

这篇关于我如何检查是否一个GNU awk的协进程是开放的,或者强迫它不写它打开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆