0

I'm trying to capture output of ltrace command using C program.

I have tried using popen() but that's not working, I need to capture continuously output not only once.

Below is my code:

#include <stdio.h>
#include <stdlib.h>

int main(int carg, char *args[]) {
    FILE *fp = popen("ltrace -p pid", "r");
    char buf[255];
    while (1) {
        if (fgets(buf, 255, fp) != NULL) {
            printf("Captured Text: %s", buf);
        }
    }
    return 0;
}

Please give me your advice

  • yes that ltrace command is in Linux, – Yougesh May 12 '18 at 15:01
1

ltrace outputs to stderr, not stdout. But popen() will read the pipe connecting the command's stdout. So this should be enough to fix it:

FILE *fp = popen("ltrace -p pid 2>&1", "r");

UPDATE: likewise, to filter directly the same ltrace command in a shell:

ltrace -p pid 2>&1 | grep someregex

ltrace's default output is to stderr so it has to be redirected to stdout to be useful for a pipe.

  • It works!!! Thank you so much. You made my day. Bravo – Yougesh May 13 '18 at 1:13
  • And need one more suggestion please, is it possible use grep command on ltrace command? I have tried regex on it but didn't work – Yougesh May 13 '18 at 1:17
  • same: ltrace .... 2>&1 | grep .... . And if you're satisfied with the answer, please to accept it. – A.B May 13 '18 at 1:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.