我对线程和进程还很陌生,我发现我无法让 CreateProcess() 启动可执行文件,尽管有很多其他论坛帖子都在讨论它。根据我对它如何工作的微薄理解,我认为我设置了正确的参数,但我收到了 Create Process failed (267)
错误。我尝试运行的可执行文件是一个命令行工具,属于名为 xst 的 Xilinx 套件。我想要的是在 path
全局变量定义的目录中运行 xst,这样它就可以处理存储在那里的一些文件。我的 CreateProcess() 参数有误吗?
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sddl.h>
#include <windows.h>
#include <AccCtrl.h>
#include <Aclapi.h>
std::string path = "C:\\FPGA\\BSP\\BSP\\Xilinx\\SingleItemTest\\";
void testXST(std::string filePath, std::string arguements) {
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
// Start the child process.
if (!CreateProcess(
LPTSTR(filePath.c_str()),
LPTSTR(arguements.c_str()),
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
LPTSTR(path.c_str()),
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
return;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
int main()
{
std::string xstPath = "C:\\Xilinx\\14.7\\ISE_DS\\ISE\\bin\\nt\\xst.exe";
std::string args = " -h";
testXST(xstPath, args);
return 0;
}
我为 xst 设置了环境变量,因此我可以从命令行的任何地方调用它,但是因为我给出了无关紧要的可执行文件的直接路径,对吗?
最佳答案
这里有几个问题。
首先,正如@PaulMcKenzie 在评论中指出的,lpCommandLine
参数的类型是LPTSTR
,而不是LPCTSTR
。因此,您不能传递 std::string::c_str()
的返回值,因为它会返回 const 缓冲区。您需要将 std::string
的内容复制到 char
数组中,并将其传递给 CreateProcess()
。
其次,您没有为 lpCommandLine
参数传递正确的值。它的值不是进程的参数,而是要执行的整个命令行。除了任何参数之外,这必须包括可执行文件的路径。将此视为您在命令提示符下键入的内容以运行相同的内容。
关于c++ - CreateProcess + 调用命令行工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37886801/