我在 Linux 上使用 libc 的 system() 时遇到问题。我的代码是这样的:
system( "tar zxvOf some.tar.gz fileToExtract | sed 's/some text to remove//' > output" );
std::string line;
int count = 0;
std::ifstream inputFile( "output" );
while( std::getline( input, line != NULL ) )
++count;
我反复运行这个片段,偶尔我发现在运行结束时 count == 0 - 没有从文件中读取任何行。我查看了文件系统,该文件具有我期望的内容(大于零行)。
我的问题是 system() 应该在传入的整个命令完成时返回,或者是否存在管道 '|'意味着 system() 可以在管道完成后的命令部分之前返回?
我明确没有使用“&”作为 system() 命令的任何部分的背景。
为了进一步阐明,我在实践中确实并行运行代码片段多次,但输出文件是一个以线程 ID 命名的唯一文件名,并且是一个静态整数,每次调用 system() 时递增。我确信每次调用 system() 时输出和读取的文件都是唯一的。
最佳答案
The system() function shall not return until the child process has terminated.
或许在失败时捕获“输出”的输出,看看它是什么?此外,检查 system
的返回值是个好主意。一种情况是您正在运行的 shell 命令失败并且您没有检查返回值。
关于c++ - system() 可以在管道命令完成之前返回吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6383907/