当通过 xcode 运行以下代码时,我得到不一致的行为。有时它会正确打印 git 版本,有时它不会打印任何内容。但 shell 命令的返回码始终为 0。关于为什么会这样的任何想法吗?我究竟做错了什么?
#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;
}
听起来很可疑,就像输出被缓冲一样,您是否考虑过刷新输出缓冲区..usefflush()
这样做。看here http://opengroup.org/onlinepubs/007908775/xsh/popen.html了解更多信息。
希望这可以帮助,
此致,
汤姆.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)