Suppress console when calling “system” in C++

前端 未结 5 1724
灰色年华
灰色年华 2020-12-17 16:57

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.

相关标签:
5条回答
  • 2020-12-17 17:09

    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");
    
    0 讨论(0)
  • 2020-12-17 17:14

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

    0 讨论(0)
  • 2020-12-17 17:14

    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

    0 讨论(0)
  • 2020-12-17 17:26

    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.

    0 讨论(0)
  • 2020-12-17 17:32

    Errm. CreateProcess or ShellExecute.

    0 讨论(0)
提交回复
热议问题