Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using popen() to invoke a shell command?

Tags:

c

popen

When running the following code through xcode I get inconsistent behavior. Sometimes it prints the git version correctly, other times it doesn't print anything. The return code from the shell command is always 0 though. 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;
}

like image 616
Anvar Avatar asked May 29 '26 18:05

Anvar


1 Answers

It sounds suspiciously like as if the output is buffered, have you considered flushing the output buffer..use fflush() to do so. See here for further information.

Hope this helps, Best regards, Tom.

like image 172
t0mm13b Avatar answered May 31 '26 08:05

t0mm13b