Suppress console when calling "system" in C++

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().


Errm. CreateProcess or ShellExecute.


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.


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");