寻找popen输出变化

时间:2014-07-30 20:15:01

标签: c linux gcc

我需要创建一个执行此操作的程序:

  • 使用popen执行命令
  • 用popen的输出做事(在很多事情中使用FILE)
  • 继续检查popen输出更改,如果有,请重新执行所有操作。

源代码在这里:https://gitorious.org/clyv/clyv

所以我只想在popen的输出发生变化时执行AGAIN的所有其余程序(必须与第一个输出进行比较) 程序应该在第一时间完成所有操作,之后,只执行所有操作并在popen输出发生更改时再次打印。 popen应该每秒验证一次。

更新

我没有得到任何解决我问题的答案,但是阅读C教程我看到了一些关于线程的内容,这听起来像是我的解决方案,我会看到我能做些什么。

3 个答案:

答案 0 :(得分:1)

您可以根据需要多次拨打popen()。但是,要正确释放呼叫popen()所使用的资源,您需要致电pclose()

在您的情况下,您可能只想偶尔轮询输出,并在必要时发出一些内容。

first_time = 1;
need_to_print = 1;
for (;;) {
    FILE *fp = popen(...);
    /* read input ... */
    pclose(fp);
    /* parse input ... */
    if (first_time) {
        /* save contents for future comparison... */
        first_time = 0;
    } else {
        need_to_print = /* result of comparing saved contents with new contents */;
    }
    if (need_to_print) {
        /* print something ... */
    }
    sleep(INTERVAL);
}

答案 1 :(得分:0)

你可以使用     //一个包含2个字符串缓冲区的数组     char输出[2] [1024];     //正在使用的字符串缓冲区索引     int flip = 0;     FILE * fp;

void executeTestCommand() {


    int resultSize;
    fp = popen("free -m | awk 'NR==3 {print $3}'" "r");
    if (fp == NULL) {
        perror("Failed to run command");
    }
    else {
        result_size = fread(output, 1, 1024 - 1, fp);
        //place string terminator
        output[flip][result_size] = '\0';
    }
    //flip the buffers
    flip = flip ^ 1;
    pclose(fp);
}


int main() {
    //init with empty string
    output[0][0] = '\0';
    output[1][0] = '\0';
    //for ever
    for(;;) {
        executeTestCommand();
        //if the last command output differs from the current
        //command output
        if (strcmp(output[0], output[1])) {
            //execute the rest of the command here
        }           
    }

    return 0;
}

干杯!

您想要关闭文件指针(您不希望任何内存泄漏),因为您将使用popen再次使用相同的FILE * fp变量。

稍后编辑:希望它有帮助:)。您可能希望在for block中插入一个sleep语句,因为这将是cpu密集型。

答案 2 :(得分:0)

@AlinUngureanu @JonathanLeffler @jxh

我在git上发布了这个源代码!现在你可以看到我想要的东西了

https://gitorious.org/clyv/clyv