Suppress console when calling “system” in C++

China☆狼群 提交于 2019-11-29 06:31:35

It sounds like you're using windows.

On Linux (and *nix in general), I'd replace the call to system with calls to fork and exec, 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.

Tim Visée

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;

#include <Windows.h>

Then you need to use the following function to run your command;

WinExec("your command", SW_HIDE); 

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;

system("your command");

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

Errm. CreateProcess or ShellExecute.

MD XF

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:

int windows_system(const char *cmd)
{
  PROCESS_INFORMATION p_info;
  STARTUPINFO s_info;
  LPSTR cmdline, programpath;

  memset(&s_info, 0, sizeof(s_info));
  memset(&p_info, 0, sizeof(p_info));
  s_info.cb = sizeof(s_info);

  cmdline     = _tcsdup(TEXT(cmd));
  programpath = _tcsdup(TEXT(cmd));

  if (CreateProcess(programpath, cmdline, NULL, NULL, 0, 0, NULL, NULL, &s_info, &p_info))
  {
    WaitForSingleObject(p_info.hProcess, INFINITE);
    CloseHandle(p_info.hProcess);
    CloseHandle(p_info.hThread);
  }
}

Works on all Windows platforms. Call just like you would system().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!