createprocess返回0,getlasterror设置为2

createprocess returning 0 with getlasterror set to 2

本文关键字:设置 getlasterror 返回 createprocess      更新时间:2023-10-16

我必须通过提供jar文件路径来执行类文件。下面是我的程序,但是createprocess返回0,getlasterror设置为2。尝试使用sysnative而不是system32,但仍然不起作用。有人能告诉我这里出了什么问题吗:

char *command;
char *cmdname = "c:\windows\system32\cmd.exe /C ";
    char *p = " java -cp ";
    char *p1 = " com.ge.med.terra.eaaa.server.EA3Server %*";
   command = (char *)malloc(50);
    env = getenv("GEHC_SECURITY_HOME");
    strcpy(command, cmdname);
    strcat(command, """);
    strcat(command, p);
    strcat(command, """);
    strcat(command,env);
    strcat(command,"\eat\jar\eat.jar";");
    strcat(command, p1);
    strcat(command, """);
    result = CreateProcessA( NULL,   // No module name (use command line)
        command,        // Command line
        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
        NULL,           // Use parent's starting directory 
        &si,            // Pointer to STARTUPINFO structure
        &pi ) ;  

您用c++标记了这个问题。出于这个原因,我建议您使用C++std::string类。这样,就可以很容易地连接创建命令所需的字符串。它更简洁,更易于阅读,所有内存管理都由后台的类完成(不需要malloc),并且您不需要担心用终止字符串(可能不是本例,但一般情况下)。以下是您的操作方法:

std::string command = "c:\windows\system32\cmd.exe /C " java -cp "" + std::string(env)
    + "\eat\jar\eat.jar";"";
result = CreateProcessA(NULL,   // No module name (use command line)
    command.c_str(),        // Command line
    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
    NULL,           // Use parent's starting directory 
    &si,            // Pointer to STARTUPINFO structure
    &pi);

您正在溢出分配的缓冲区。您为50个字符分配了空间,但您编写了105个字符加上GEHC_SECURITY_HOME中的任何字符。当这种情况发生时,您将写入其他分配的块,这将产生未指定但不希望的行为。

使用std::string可以消除这种情况,但+运算符的速度较慢。如果您关心性能,那么使用std::stringstream会更好。但为了测试这是否是唯一的问题,你可以把50改成500左右,然后再试一次。