system() to c++ without calling cmd.exe

2019-07-29 03:47发布

问题:

how can I run system("") without showing cmd.exe?

I use cstdlib header code::blocks 10.5

I saw this question for c# but I don't know c# ;)

回答1:

I believe you'll have to go with CreateProcess instead.



回答2:

I must say, the existing answer wasn't particularly descriptive. Here's a way to execute commands without a new cmd.exe window.

Based on an answer by Roland Rabien 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().



标签: c++ c cmd