Using popen () to invoke a shell command?

When I run the following code through xcode, I get inconsistent behavior. Sometimes it prints the git version correctly, in other cases it does not print anything. The return code from the shell command is always 0. Any ideas on why this might be? What am I doing wrong?


#define BUFFER_SIZE 256 
int main (int argc, const char * argv[])  
{   
    FILE *fpipe;
    char *command="/opt/local/bin/git --version";
    char line[BUFFER_SIZE];

    if ( !(fpipe = (FILE*)popen(command, "r")) )
    {   // If fpipe is NULL
        perror("Problems with pipe");
        exit(1);
    }

    while ( fgets( line, sizeof(char) * BUFFER_SIZE, fpipe))
    {
         // Inconsistent (happens sometimes) 
         printf("READING LINE");
         printf("%s", line);
    }

    int status = pclose(fpipe);

    if (status != 0)
    {
        // Never happens
        printf("Strange error code: %d", status);
    }

    return 0;
}

+3
source share
2 answers

I think I found a source of strange behavior. Xcode seems to be doing something funky in the built-in terminal window, which leads to the fact that I don't see the output. If I try to run the code directly in the standard terminal window, this behavior will not appear, and the text will be printed out sequentially.

+1
source

, , , ... use fflush(). . .

, , , .

+1

Source: https://habr.com/ru/post/1728637/


All Articles