tags:

views:

157

answers:

2

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;
}

+1  A: 

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.

tommieb75
I originally had that in my code but decided to remove it before pasting it here :) Did not seem to help though :(
Anvar
It seems to me that is for when the parent program is outputing data. The fflush() in this case would have to be done at the git's side. Often programmers ignore this as when a process closes the OS flushes all buffers.
Hassan Syed
A: 

I think I have found the source of the strange behavior. It seems as Xcode is doing something funky in the built in terminal window which results in me not seeing the output. If I try to run the code directly in a standard terminal window this behavior does not appear, and the text is consistently printed out.

Anvar
Now that you mention it, I have had that problem with eclipse -- with eclipse it was a missing flush.
Hassan Syed
Interesting, I tried adding fflush, but it did not seem to help - might be just me doing it wrong though. Could you maybe point out to me on which line to add fflush?
Anvar