Sunny
Sunny

Reputation: 7604

C Multiple processes: Program crashes while creating child process

I am trying to create a child process with the following command:

    STARTUPINFO si;
    PROCESS_INFORMATION pi;    
    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );


  CreateProcess( NULL,   // No module name (use command line)
        NULL,           // 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 ); 

It crashes over here and I am not sure why.

  1. Now my original process takes command line parameters, so do I have to pass them here also? If so then since I am not creating child process from int main() so can I do the following:

    LPTSTR szCmdline = TEXT("nmctest -s TS -r DMR -tlLDMR");

Then pass szCmdline inside CreateProcess()?

Can someone please help me why this is crashing?

Upvotes: 0

Views: 252

Answers (1)

David Heffernan
David Heffernan

Reputation: 613053

Your code is failing because you are passing NULL for both lpApplicationName and lpCommandLine. You must pass a value for at least one of them. The documentation makes that clear.

It looks like you have also attempted to pass a value to lpCommandLine. But you have passed a non-modifiable string literal. Again the documentation makes it clear that is not allowed. Pass a pointer to memory that can be modified.

The Unicode version of this function, CreateProcessW, can modify the contents of this string. Therefore, this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string). If this parameter is a constant string, the function may cause an access violation.

You can meet that requirement like this:

TCHAR szCmdline[] = _T("nmctest -s TS -r DMR -tlLDMR");

Personally, I see no need for TCHAR in this day and age. Surely you aren't still writing programs for Windows 98? I would do it like so:

wchar_t szCmdline[] = L"nmctest -s TS -r DMR -tlLDMR";

The other possible failure vector in your code is the STARTUPINFO parameter. Make sure that you have initialised that correctly. The most simply way to do that is like so:

STARTUPINFO si = {0};
si.cb = sizeof(si);

But you might like to add a call to GetStartupInfo.

STARTUPINFO si = {0};
si.cb = sizeof(si);
GetStartupInfo(&si);

Upvotes: 3

Related Questions