创建进程在转换项目以支持 Unicode 后不运行 .cmd 文件
CreateProcess doesn't run .cmd file after converting project to support Unicode
我已经改变了一个旧的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
支持时需要做的任何事情吗?
注:我调试并检查了所有的参数。他们看起来很好。sCommandLine
是PROCESS_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构建。
相关文章:
- 如何在使用Makefile构建后在cmd中运行该程序?
- 父进程意外被子 cmd 杀死.exe运行 java jar 的进程 - WINDOWS 7 问题 - C++
- 使用 system() 函数在C++程序中运行 cmd 命令
- 从Visual Studio 2017运行MPI应用程序,每个进程在不同的cmd窗口中
- 如何将我的程序转换为.dll文件并使用rundll32.exe在cmd中运行它?
- 从 CMD 运行.exe并自动向其传递参数
- 如何在Powershell中运行C++程序,就像CMD一样?
- 在CMD中运行MATLAB代码,然后等待完成
- 如何将控制台输出的文本颜色更改为红色,但如果从Powershell或CMD运行,背景将保持相同的颜色
- 如何从Windows CMD运行可执行文件并将其传递给文件输入的参数参数和重定向
- 在C++中运行 CMD 行 使用变量(不是字符串文字)作为参数
- 检查我的 C++ 代码!我的cmd屏幕在运行后关闭!我的错误可能是什么
- 在cmd中运行程序时出现问题
- 如何在C++上以管理员身份运行cmd命令
- 如何在 Windows 操作系统中创建制作文件并使用 cmd 运行它
- 运行CMD命令并将结果获取到字符串变量
- c ++如何使运行时间显示在cmd上?作为运行时钟,需要更改系统("clear")?
- 随时随地运行,使用 C++ 更改 CMD 命令
- 创建进程在转换项目以支持 Unicode 后不运行 .cmd 文件
- 如何运行CMD脚本,而不是构建和启动c++控制台应用程序