0

Possible Duplicate:
Run a simple shell command

Is there a Win32 API function that does the same thing as system() in a similarly simple way? In the specific console program I'm creating, I'd like to limit as much as possible to the Windows libraries.

Community
  • 1
  • 1
Archimaredes
  • 1,397
  • 12
  • 26

3 Answers3

2

Is there some reason CreateProcess is no good?

user1701047
  • 737
  • 5
  • 7
  • `system()` calls `CreateProcess()` internally, launching the OS command-line interpreter - CMD.EXE or COMMAND.COM - to run the specified command. So you can just call `CreateProcess()` directly to do the same thing. – Remy Lebeau Oct 17 '12 at 19:42
  • Yeah. I didn't get a clarification from the OP as to why this wasn't good enough. As I recall it is non-OS specific--it just sends to the terminal/command/etc., i.e. on linux it will run the command through terminal. I've never really used it though, I just know of its existence as I've never had to use it in C++ myself. (I'm sure I've used a class that wrapped around it though in C# or anything that debugged through the console window.) – user1701047 Oct 18 '12 at 16:35
2

You can just use system().

The system function finds the command interpreter, which is typically CMD.EXE in the Windows NT operating system or COMMAND.COM in Windows. The system function then passes the argument string to the command interpreter.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • I think we need more information. I also do not understand why either of our ideas don't seem to be what they're looking for. – user1701047 Oct 17 '12 at 17:07
  • Actually, never mind. As system() is exported by msvcr110.dll, it doesn't make any difference anyway. I meant to ask if there happened to exist a function that was strictly part of the Win32 API that was equivalent to system(), but I see it's not required in place of system() now. – Archimaredes Oct 17 '12 at 17:11
1

system() just calls CreateProcess() internally, so you can do the same thing directly, eg:

int my_system(LPCTSTR command)
{
    TCHAR szComSpec[MAX_PATH+1];
    DWORD dwLen = GetEnvironmentVariable(_T("COMSPEC"), szComSpec, MAX_PATH);
    if ((dwLen == 0) || (dwLen > MAX_PATH))
        return -1;

    LPTSTR szCmdLine = (LPTSTR) LocalAlloc(LPTR, (dwLen+lstrlen(command)+9) * sizeof(TCHAR));
    if (!szCmdLine)
        return -1;

    wsprintf(szCmdLine, _T("\"%s\" /C \"%s\""), szComSpec, command);

    STARTUPINFO si;
    ZeroMemory(&si, sizeof(si));
    si.cbSize = sizeof(si);
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE;

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(pi));

    BOOL bRet = CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
    if (bRet)
    {
        CloseHandle(pi.hThread);
        CloseHandle(pi.hProcess);
    }

    LocalFree(szCmdLine);

    return (bRet) ? 0 : -1;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770