How can I check if a GNU awk coprocess is open, or force it to open without writing to it?

ε祈祈猫儿з 提交于 2019-12-10 18:59:50

问题


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)
}

回答1:


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)
}


来源:https://stackoverflow.com/questions/24066356/how-can-i-check-if-a-gnu-awk-coprocess-is-open-or-force-it-to-open-without-writ

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!