CreateProcess执行Windows命令

Oum*_*aya 2 windows winapi cmd createprocess

我正在尝试使用CreateProcess函数执行dos命令:

 LPWSTR cmd=(LPWSTR)QString("C:\\windows\\system32\\cmd.exe  subst " + DLetter+"  \""+mountPath+"\"").utf16();



        STARTUPINFO si;
        PROCESS_INFORMATION pi;
        ZeroMemory( &si, sizeof(si) );
        si.cb = sizeof(si);
        ZeroMemory( &pi, sizeof(pi) );

        if ( CreateProcessW(0,     // Application name
                           cmd,                 // Application arguments
                           NULL,
                           NULL,
                           TRUE,
                           0,
                           NULL,
                           L"C:\\windows\\system32",          // Working directory
                           &si,
                           &pi) == TRUE)
        { ...
Run Code Online (Sandbox Code Playgroud)

它给出了最后一个错误3 = ERROR_PATH_NOT_FOUND,当我将应用程序路径"C:\\windows\\system32\\cmd.exe"与命令分开时,它显示控制台而不执行我的subst命令.

任何帮助将不胜感激.

Dav*_*nan 5

您需要在选项要么/ C或/ K cmd.exe.

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains

如果没有这些选项,subst您传递的命令将被忽略.

话虽如此,subst至少在我的Windows 7机箱上,并没有在里面实现cmd.exe.它是一个单独的可执行文件 所以你可以直接调用它并cmd.exe完全绕过它.

关于你的来电,CreateProcess我有以下意见:

  1. 不要包含路径C:\\windows\\system32.只需调用subst.exe并让系统使用标准搜索路径找到可执行文件.
  2. 通过FALSEbInheritHandles.您没有将任何句柄传递给新进程,因此您不需要新进程来继承句柄.
  3. 传递NULL为工作目录.这里没有必要指定它.

  • @DavidHeffernan:更好的是,不要使用`subst`可执行文件来操纵驱动器映射.直接使用Win32 API函数,例如`DosDefineDevice()`,`WNetAddConnection ...()`,`WNetCancelConnection ...()`等. (3认同)