當通過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