当通过xcode运行下面的代码时,我得到不一致的行为。有时它会正确打印git版本,有时它不会打印任何内容。虽然shell命令的返回码始终为0。任何想法,为什么这可能是?我究竟做错了什么?使用popen()来调用shell命令?
#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;
}
现在你提到它了,我在eclipse上遇到了这个问题 - 在eclipse中它是一个缺失的flush – 2010-01-16 14:31:22
有趣的是,我尝试添加fflush,但它似乎没有帮助 - 可能只是我做错了,但你可能会指出我在哪一行添加fflush? – Anvar 2010-01-16 18:00:38
看来,在eclipse终端窗口中,最后一个如果不在printf语句的末尾添加换行符(\ n),则不显示输出行。 – 2013-11-21 11:21:54