如何反复运行C代码直到获得一些stdout?

我想调试由随机过程运行的代码的某些情况。

所以我将printf放在我要调试的部分的代码中。

在得到printf语句之前,有什么方法可以在终端上运行此代码?

我想像运行shell程序

while true;
if [ "$(./mycode || grep "statement")"];
then break;
done;

(它不是可运行的,我只是想告诉您语义。)

但是我想if语句中的每个返回值都为true。

评论
  • 劫走EXO
    劫走EXO 回复

    If you want to quit as soon as you see the line in question it's best to avoid grep. It may have an internal buffer and try to read past the matching line. The same goes for sed, and most other programs in fact.

    I would use an explicit while read loop. read never reads more than one line so it won't overshoot.

    #!/bin/bash
    
    ./mycode | while IFS= read -r line; do
        [[ $line == *'statement'* ]] && break
    done
    

    语法可能看起来很奇怪,将输出传递到一个循环中。之所以有效,是因为循环实际上只是一个大的复合命令。确实,这是一个巧妙的技巧。

    如果要使其更具可读性,可以将循环重构为一个函数。

    #!/bin/bash
    
    read_until() {
        while IFS= read -r line; do
            [[ $line == *"$1"* ]] && break
        done
    }
    
    ./mycode | read_until 'statement'
    

    笔记:

    • I'm using bash features above so you'll need a #!/bin/bash shebang line to use them.
    • IFS= read -r is standard boilerplate to make the read call safer. IFS= prevents it from stripping leading whitespace, and -r tells it to leave backslashes alone. For historical reasons these are opt-out features not opt-in.