我想从我的 C++ 代码运行另一个程序。 system()
返回 int,因为每个程序只能将 int 返回给操作系统。但是,我要调用的另一个程序将生成我的基本应用程序中需要的字符串。如何将它发送给父进程?
这两个应用程序将在同一个文件夹中,所以我认为子应用程序可以将字符串保存到“temp.txt”,然后主应用程序可以读取并删除它(这不是性能关键过程,我会调用另一个进程只是在我的主要 opengl 应用程序中调用打开文件对话框)。然而这是一个有点丑陋的解决方案,有没有更好的跨平台解决方案?
谢谢
最佳答案
你可以使用 popen()
,这将打开一个进程,您可以在其中写入和读取数据。 AFIK 这也是跨平台
// crt_popen.c
/* This program uses _popen and _pclose to receive a
* stream of text from a system process.
*/
#include <stdio.h>
#include <stdlib.h>
int main(void) {
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. */
while(!feof(pPipe)) {
if(fgets(psBuffer, 128, pPipe) != NULL)
printf(psBuffer);
}
/* Close pipe and print return value of pPipe. */
printf("\nProcess returned %d\n", _pclose(pPipe));
return 0;
}
关于c++ - 如何在 C++ 中运行另一个应用程序并与之通信,跨平台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13978162/