Search code examples
csystem

C run external program get error


In my C code I want to run an external program. For this I use system() function like this example:

system("/bin/myprog");

But I want to detect if my external program have error or not exit correctly. How can I get the error?


Solution

  • If you want to get the error message then you need to trap the stderr from the external program. Note that popen traps stdout, so you need to redirect using the shell construct 2>&1 (fortunately popen also runs a shell). For example:

    #define BUFF_SIZE 1024
    
    int main()
    {
        char buffer[BUFF_SIZE];
    
        FILE *p = popen("/bin/myprog 2>&1", "r");
    
        while (fgets(buffer, BUFF_SIZE, p))
            printf("Recieved: %s\n", buffer);
    
        return 0;
    }
    

    EDIT: To ignore stdout messages and only get stderr messages then use:

    FILE *p = popen("/bin/myprog 2>&1 1>/dev/null", "r");