Search code examples
c++windowscodeblockscreateprocess

Problem with CreateProcessA() windows 10 c++ code::blocks


I have a problem with CreateProcessA, I looked at all the questions about it on stackoverflow and other sites, I rewrote a program following the advice of others but it still does not execute any commands and return error 998. I'm sure the string is correct because it works both with system and written directly on cmd. I really don't know what to do anymore. I've also read how it works but doesn't want to work. Sorry if my english is bad, thanks to those who answer me.

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
    STARTUPINFOA si;
    si.cb = sizeof(si);
    PROCESS_INFORMATION pi;
    string com="\"C:\\Program Files\\MKVToolNix\\mkvextract.exe\" \"D:\\Anime recuperati\\BKT\\Caricati\\[BKT] Jormungand 01-12 END BDRip\\Jormungand - Ep01.mkv\" attachments -f 1:\"C:\\Users\\Utente\\Desktop\\Subs\\n\\Jormungand - Ep01\\Justus-Bold.ttf\"";
    CreateProcessA(NULL,const_cast<char *>(com.c_str()),NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);
    cout<<GetLastError();
    return 0;
}

Solution

  • You pass uninitialized STARTUPINFOA si;. It must be initialized. See the example.

    #include <iostream>
    #include <string>
    #include <windows.h>
    
    using std::cout;
    using std::string;
    
    int main()
    {
        STARTUPINFOA si{sizeof(si)};
        PROCESS_INFORMATION pi{};
        string com = R"("C:\Program Files\MKVToolNix\mkvextract.exe" "D:\Anime recuperati\BKT\Caricati\[BKT] Jormungand 01-12 END BDRip\Jormungand - Ep01.mkv" attachments -f 1:"C:\Users\Utente\Desktop\Subs\n\Jormungand - Ep01\Justus-Bold.ttf)";
        CreateProcessA(nullptr, const_cast<char *>(com.c_str()), nullptr, nullptr, false, 0, nullptr, nullptr, &si, &pi);
        cout<<GetLastError();
        return 0;
    }
    
    1. #include <string> if you use std::string.
    2. Use R"(...)" to avoid using escape sequences.
    3. Use nullptr in C++.
    4. Use false in C++.
    5. Why is using namespace std; considered bad practice?