我需要构建一个控制台应用程序(A),它显示一个菜单,您可以在其中选择一个选项,它将执行我在类里面构建的以前的控制台应用程序(B,C,D ...)。我该怎么办?我可以调用这些以前的应用程序还是需要将它们添加到我的程序中?因为它需要包含大约 15 个以前的项目,我认为这有点过分了。我知道 fOpen()
用于打开 txt 文件,但我不知道它是否适用于应用程序。 FILE *fopen( const char * 文件名, const char * 模式);
最佳答案
您需要启动一个子进程,然后将其 stdout
重定向到您自己的进程的输出,并将其 stdin
重定向到您自己的进程进程的输入 - 但您可能希望拦截某些击键,以允许用户终止子进程而不杀死您自己的进程。
在 POSIX 环境中,您可以使用 popen()
,它为您提供用于重定向输入和输出的管道。在 Windows 上,您可以使用 CreatePipe 来代替。 Windows 没有实现 POSIX popen()
,但它确实有一个内部函数 _popen
,但我知道它有不同的语义。
但是 C 标准库中没有在进程之间进行管道传输的函数或能力(C 本身甚至不需要计算机支持“进程”的概念 - 令人惊讶的是,它是一种与平台无关的语言和库 -您甚至可以将它用于没有 malloc
实现的平台)。
无论如何,如果您愿意只针对 Windows,或者愿意编写包装器库,我建议您阅读这篇 MSDN 文章,它准确描述了您想要执行的操作:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
Creating a Child Process with Redirected Input and Output
The example in this topic demonstrates how to create a child process using the CreateProcess function from a console process. It also demonstrates a technique for using anonymous pipes to redirect the child process's standard input and output handles. Note that named pipes can also be used to redirect process I/O.
关于C - 在另一个控制台应用程序中运行控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46107259/