创建进程在转换项目以支持 Unicode 后不运行 .cmd 文件

CreateProcess doesn't run .cmd file after converting project to support Unicode

本文关键字:运行 cmd 文件 Unicode 支持 进程 转换 项目 创建      更新时间:2023-10-16

我已经改变了一个旧的MFC应用程序来支持Unicode。现在代码如下所示。这里调用的是。cmd文件

STARTUPINFO StartupInfo;
DWORD dwErrorCode;
PROCESS_INFORMATION * processInformation = new PROCESS_INFORMATION[2];
for (int i = 0; i < 2; i++)
{
    GetStartupInfo(&StartupInfo);
    if (processList[i].bHide)
    {
        StartupInfo.dwFlags |= STARTF_USESHOWWINDOW;
        StartupInfo.wShowWindow = SW_HIDE;
    }
    if (processList[i].sCustomTitle.GetLength())
        StartupInfo.lpTitle = processList[i].sCustomTitle.GetBuffer(processList[i].sCustomTitle.GetLength());
    CreateProcess(NULL, 
        /*I changed LPSTR to LPWSTR*/(LPWSTR)(LPCTSTR)processList[i].sCommandLine,
        NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartupInfo, &processInformation[i]);
    [...]
}

我所做的唯一更改是将LPSTR更改为LPWSTR。在转换为Unicode之前,这个工作没有任何问题。但现在它不运行了。原因是什么呢?我错过了转换到Unicode支持时需要做的任何事情吗?

注:我调试并检查了所有的参数。他们看起来很好。sCommandLinePROCESS_STARTUP_INFO struct中的CString变量

正如在注释中提到的,您不应该强制转换字符串。您应该使用临时变量,因为文档中有以下注释:

这个函数的Unicode版本CreateProcessW可以修改这个字符串的内容。因此,该形参不能是指向只读内存的指针(如const变量或字面值字符串)。如果该参数是一个常量字符串,该函数可能导致访问冲突。

最近我有一个类似的问题。我用下面的方法解决了这个问题(我试图使它防弹):

// The maximum length of the command line string is 32,768 characters,
// including the Unicode terminating null character.
#define MAX_CMD_LINE_LEN 32768
// Use a temporary variable for the command line.
TCHAR szCmdLine[MAX_CMD_LINE_LENGTH];
// Get the length of the command line. Crop the command line if it is too long.
int iLen = min(processList[i].sCommandLine.GetLength(), MAX_CMD_LINE_LEN - 1);
// Copy the command line string to the temporary variable.
_tcsncpy_s(szCmdLine, processList[i].sCommandLine, iLen);
// Create the process by passing the temporary variable holding a copy of your
// original command line string.
CreateProcess(NULL, 
              szCmdLine,
              NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL,
              NULL, &StartupInfo, &processInformation[i]);

此解决方案应该可以编译并工作于Unicode和非Unicode构建。