如果从文件中读取,则无法按文件名运行进程

Can't run process by Filename if read from file

本文关键字:文件名 运行 进程 文件 读取 如果      更新时间:2023-10-16
LPCSTR      __FileName = "program.exe";   
void ProcessRun(LPCSTR pszExeName)
    {
        PROCESS_INFORMATION piProcInfoGPS;
        STARTUPINFO siStartupInfo;
        SECURITY_ATTRIBUTES saProcess, saThread;
        ZeroMemory(&siStartupInfo, sizeof(siStartupInfo));
        siStartupInfo.cb = sizeof(siStartupInfo);
        saProcess.nLength = sizeof(saProcess);
        saProcess.lpSecurityDescriptor = NULL;
        saProcess.bInheritHandle = true;
        saThread.nLength = sizeof(saThread);
        saThread.lpSecurityDescriptor = NULL;
        saThread.bInheritHandle = true;
        CreateProcess(NULL, (LPTSTR)pszExeName, &saProcess, &saThread, false, CREATE_DEFAULT_ERROR_MODE, NULL, NULL, &siStartupInfo, &piProcInfoGPS);
        __hProcess = piProcInfoGPS.hProcess;
        __ProcessID = piProcInfoGPS.dwProcessId;
    }

如果我__FileName传递给函数,程序将运行。但是,当我从 ini 文件中读取文件名时

[Launcher]
FileName=program.exe

char INIValue[256];
GetPrivateProfileString("Launcher", "FileName", "nan.exe", INIValue, 256, ".\BackgroundConfig.ini");
string temp(INIValue);
__FileName = temp.c_str();

然后尝试将文件名传递给函数,它不会运行。到底是什么原因造成的?文件名完全相同。

您尚未显示足够的代码来确定这是问题所在,但请考虑以下事项:

char * someString;
void foo()
{
    std::string str("whatever");
    doSomethingWithCharStar(str.c_str()); // fine: str's data has not been destroyed yet
    someString = str.c_str();
} // uh-oh, here the std::string's memory will be deleted
void bar()
{
    foo(); // sets someString
    doSomethingWithCharStar(someString); // by the time we get here, though, the memory pointed to by someString is freed
}

上面的代码调用未定义的行为(假设doSomethingWithCharStar取消引用传入的指针)。不应将char*存储为全局,而应存储std::string。更好的是,根本不要使用全局:

std::string foo()
{
    return std::string("whatever");
}
void bar()
{
    std::string value(foo());
    doSomethingWithCharStar(value.c_str());
}

请注意,在上面的第一个代码段中遇到的问题本质上与返回对局部变量的引用时的问题相同。