调用“系统”时抑制控制台在 C++
我在 C++ 中使用 system
命令来调用一些外部程序,每当我使用它时,控制台窗口都会在命令完成后打开和关闭。
如何避免打开控制台窗口?如果解决方案可以独立于平台,我会很高兴。我还想让我的程序等到命令完成。
I'm using the system
command in C++ to call some external program, and whenever I use it, a console window opens and closes after the command finishes.
How can I avoid the opening of a console window? I would be happy if the solution could be platform-independent. I would also like for my program to wait until the command is finished.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这可能是最简单也可能是最好的方法,这也将使您的程序在运行此命令时不会冻结。
首先不要忘记使用以下命令包含 Windows 标头:
然后你需要使用以下函数来运行你的命令;
注意;
WinExec
方法已被弃用十多年了。但今天它仍然运行良好。如果不需要,您不应使用此方法。...而不是您不想要使用的方式;
This is probably the easiest and maybe the best way, this will also make it so that your program doesn't freeze while running this command.
At first don't forget to include the Windows header using;
Then you need to use the following function to run your command;
Note; The
WinExec
method has been deprecated for over a decade. It still works fine today though. You shouldn't use this method if not required.... instead of the way you don't want to use;
听起来你用的是windows。
在 Linux(以及一般的 *nix)上,我将对
system
的调用分别替换为对fork
和exec
的调用。在 Windows 上,我认为 Windows API 中有某种“生成新进程”函数——请参阅文档。当您运行 shell 命令和/或外部程序时,您的程序很难使平台无关,因为它将取决于具有您正在运行的命令和/或外部程序的平台。
It sounds like you're using windows.
On Linux (and *nix in general), I'd replace the call to
system
with calls tofork
andexec
, respectively. On windows, I think there is some kind of spawn-a-new-process function in the Windows API—consult the documentation.When you're running shell commands and/or external programs, your program is hard to make platform-independent, as it will depend on the platform having the commands and/or external programs you're running.
这是一种无需新的
cmd.exe
窗口即可执行命令的方法。基于Roland Rabien的回答和MSDN,我编写了一个工作函数:适用于所有 Windows 平台。就像调用
system()
一样进行调用。Here's a way to execute commands without a new
cmd.exe
window. Based on Roland Rabien's answer and MSDN, I've written a working function:Works on all Windows platforms. Call just like you would
system()
.呃。
CreateProcess
或ShellExecute
。Errm.
CreateProcess
orShellExecute
.exec() 看起来非常独立于平台,因为它是 POSIX。在 Windows 上,它是 _exec(),而在 unix 上它是 exec():请参阅 http://msdn.microsoft.com/en-us/library/431x4c1w(VS.71).aspx
exec() looks quite platform independant as it is POSIX. On windows, it's _exec() while it's exec() on unix: See http://msdn.microsoft.com/en-us/library/431x4c1w(VS.71).aspx