3

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

4

2 回答 2

1

我想我已经找到了奇怪行为的根源。似乎 Xcode 在内置终端窗口中做了一些时髦的事情,导致我看不到输出。如果我尝试直接在标准终端窗口中运行代码,则不会出现此行为,并且会始终打印出文本。

于 2010-01-15T22:55:28.427 回答
1

听起来好像输出被缓冲了一样可疑,您是否考虑过刷新输出缓冲区..fflush()使用这样做。请参阅此处了解更多信息。

希望这会有所帮助,最好的问候,汤姆。

于 2010-01-15T15:50:43.240 回答