Reputation: 2739
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.
Upvotes: 15
Views: 12716
Reputation: 8129
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()
.
Upvotes: 3
Reputation: 3248
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");
Upvotes: 6
Reputation: 12165
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
Upvotes: 0
Reputation: 7837
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.
Upvotes: 4