我想从父进程启动一个可执行文件。等到该进程完成,然后读回它写入 stdout 的内容。事实证明,您不能等待程序完成然后读取 FILE* 流,因为等待它完成意味着调用 pclose(FILE*),到那时文件流将被销毁。在 Windows 文档中,它说要这样做:
char psBuffer[128];
FILE* pPipe;
/* Run DIR so that it writes its output to a pipe. Open this
* pipe with read text attribute so that we can read it
* like a text file.
*/
if ((pPipe = _popen("dir *.c /on /p", "rt")) == NULL)
{
exit(1);
}
/* Read pipe until end of file, or an error occurs. */
while (fgets(psBuffer, 128, pPipe))
{
puts(psBuffer);
}
int endOfFileVal = feof(pPipe);
int closeReturnVal = _pclose(pPipe);
if (endOfFileVal)
{
printf("\nProcess returned %d\n", closeReturnVal);
}
else
{
printf("Error: Failed to read the pipe to the end.\n");
}
它打开管道,然后立即从流中读取。由于读取是在启动子进程后立即执行的,所以它很可能会读取流,但流为空或到达文件末尾,这种情况不是吗?为什么这是有效的?