CreateProcess Access violation(越界访问)

https://stackoverflow.com/questions/11339186/createprocess-fails-with-an-access-violation

My aim is to execute an external executable in my program. First, I used system() function, but I don't want the console to be seen to the user. So, I searched a bit, and found CreateProcess() function. However, when I try to pass a parameter to it, I don't know why, it fails. I took this code from MSDN, and changed a bit:

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

void _tmain( int argc, TCHAR *argv[] )
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );
    /*
    if( argc != 2 )
    {
        printf("Usage: %s [cmdline]\n", argv[0]);
        return;
    }
    */
    // Start the child process. 
    if( !CreateProcess( NULL,   // No module name (use command line)
        L"c:\\users\\e\\desktop\\mspaint.exe",        // 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 )           // 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 );
}

 

However, this code crated access violation somehow. Can I execute mspaint without showing user the console?

Thank you very much.

  • 2
    For one thing, CreateProcess requires that its second parameter (if provided) be a non-const string. I'm not sure that this is a problem in practice, but I wanted to mention it for completeness. – reuben Jul 5 '12 at 6:56
  •  
    ...and otherwise, where the is AV happening? Do you have a call stack? – reuben Jul 5 '12 at 6:57
  •  
    @reuben Uhm... I'm not quite sure, but I guess this is the output of call stack:kernel32.dll!76da70ac() [Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll] > msvcr100d.dll!_nh_malloc_dbg(unsigned int nSize, int nhFlag, int nBlockUse, const char * szFileName, int nLine) Line 302 + 0x1d bytes C++ – John Doe Jul 5 '12 at 7:03

3 Answers

Try this, it should work.

TCHAR lpszClientPath[500]= TEXT("c:\\users\\e\\desktop\\mspaint.exe");
if(!CreateProcess(NULL, lpszClientPath, NULL, NULL, FALSE,  NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE|CREATE_UNICODE_ENVIRONMENT,NULL, NULL, &si, &pi))
{
    printf( "CreateProcess failed (%d).\n", GetLastError() );
        return;
}
 
posted @ 2018-10-23 14:51  余生以学  阅读(453)  评论(0编辑  收藏  举报