pclose()
的手册页面如下所示:
pclose()函数等待相关进程终止,并返回由wait4(2)返回的命令的退出状态。
我认为这意味着,如果使用popen()
打开具有类型"r"
以读取command
的输出的相关FILE*
,那么在调用pclose()
之后,你才能确信输出已经完成。但是,在pclose()
之后,关闭的FILE*
肯定是无效的,那么你怎么能确定已经读取了command
的全部输出呢?
为了通过示例说明我的问题,请考虑以下代码:
// main.cpp
#include <iostream>
#include <cstdio>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
int main( int argc, char* argv[] )
{
FILE* fp = popen( "someExecutableThatTakesALongTime", "r" );
if ( ! fp )
{
std::cout << "popen failed: " << errno << " " << strerror( errno )
<< std::endl;
return 1;
}
char buf[512] = { 0 };
fread( buf, sizeof buf, 1, fp );
std::cout << buf << std::endl;
// If we're only certain the output-producing process has terminated after the
// following pclose(), how do we know the content retrieved above with fread()
// is complete?
int r = pclose( fp );
// But if we wait until after the above pclose(), fp is invalid, so
// there's nowhere from which we could retrieve the command's output anymore,
// right?
std::cout << "exit status: " << WEXITSTATUS( r ) << std::endl;
return 0;
}
我的问题如上所述:如果我们只能确保使用pclose()
后输出产生的子进程已经终止了,那么我们怎么知道使用fread()
检索到的内容是完整的呢?但是如果我们等到pclose()
之后再检索内容,fp
会无效,因此我们不能再从中检索命令的输出了,对吗?
这感觉像一个鸡生蛋的问题,但我在很多地方都看到类似上面的代码,所以我可能理解错了什么。我很感谢您对此进行解释。