CreateProcessW()为什么不执行提供的命令?

问题描述 投票:0回答:1

为了显示最小的可复制代码,我编写了一个代码,使用CreateProcessW()从给定位置删除文件。该文件不会被删除。一些帮助对于了解为什么不起作用非常有用。

    dprintf(("Error %d", GetLastError()));
    STARTUPINFO si = { sizeof(STARTUPINFO), 0 };
    si.cb = sizeof(si);
    PROCESS_INFORMATION pi = { 0 };
    LPWSTR AppName = L"C:\\Windows\\System32\\cmd.exe";
    string bstr = "C:\\Windows\\System32\\cmd.exe /C del"+trans_loc+"a.rtf";
    LPWSTR Command = new WCHAR[bstr.length()];
    int wchars_num = MultiByteToWideChar(CP_UTF8, 0, bstr.c_str(), -1, NULL, 0);
    MultiByteToWideChar(CP_UTF8, 0, bstr.c_str(), -1, Command, wchars_num);
    DWORD res = CreateProcessW(AppName, Command, 0, 0, 0, DETACHED_PROCESS, 0, 0, &si, &pi);

    WaitForSingleObject(pi.hProcess, INFINITE);

定义TRANSCRIPT_LOCATION“ C:\ Users \ Administrator \ Desktop \”,这是要删除的文件的位置

GetLastError()继续返回50(ERROR_NOT_SUPPORTED),并且res的值= 1

c++ windows createprocess
1个回答
0
投票

我的第一个想法是

LPWSTR Command = new WCHAR[bstr.length()];

不正确。也许

LPWSTR Command = new WCHAR[bstr.length() + 1];

将起作用。更好的选择是使用wchars_num分配内存。

代替

LPWSTR Command = new WCHAR[bstr.length()];
int wchars_num = MultiByteToWideChar(CP_UTF8, 0, bstr.c_str(), -1, NULL, 0);
MultiByteToWideChar(CP_UTF8, 0, bstr.c_str(), -1, Command, wchars_num);
DWORD res = CreateProcessW(AppName, Command, 0, 0, 0, DETACHED_PROCESS, 0, 0, &si, &pi);

使用

int wchars_num = MultiByteToWideChar(CP_UTF8, 0, bstr.c_str(), -1, NULL, 0);
LPWSTR Command = new WCHAR[wchars_num];
MultiByteToWideChar(CP_UTF8, 0, bstr.c_str(), -1, Command, wchars_num);
DWORD res = CreateProcessW(AppName, Command, 0, 0, 0, DETACHED_PROCESS, 0, 0, &si, &pi);
© www.soinside.com 2019 - 2024. All rights reserved.