Search code examples
coutputstdoutpopenqemu

Why does popen not grab the output of qemu?


This below code works for things like /bin/ls and other programs but not for qemu. How can i get the output stream of qemu with popen? I ran qemu-x86_64 -d cpu /bin/ls and expected to get the same output as qemu but with a "read: "before it. When i run this i just just the normal qemu output in the console.

int main()
{

        /* Call program */
        FILE* file = popen("/bin/ls", "r");
        if(file == NULL)
        {
            perror("popen");
            return 0;
        }

        /* output stream of program*/
        char *out = NULL;
        size_t outlen = 0;

        /*iterate through program output stream line by line */
        while (getline(&out, &outlen, file) >= 0) 
        {
            /* print output stream */
            printf("read: %s", out);
        }

        /* cleanup */
        pclose(file);
        free(out);
         
        return 0;
}

Solution

  • As @rici pointed out qemu actually does not print to stdout. Qemu prints to stderr and to redirect the output from stderr to stdout for popen to catch it i simply need to add 2>&1 behind the executed command.

    So instead of running:

    FILE* file = popen("qemu-x86_64 -d cpu /bin/ls", "r");
    

    I need to run:

    FILE* file = popen("qemu-x86_64 -d cpu /bin/ls 2>&1", "r");