CreateProcess() 因访问冲突而失败

标签 c winapi createprocess

<分区>

我的目标是在我的程序中执行一个外部可执行文件。首先,我使用了 system() 函数,但我不想让用户看到控制台。所以,我搜索了一下,找到了 CreateProcess() 函数。但是,当我尝试将参数传递给它时,我不知道为什么,它失败了。我从 MSDN 中获取了这段代码,并做了一些改动:

#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 );
}

但是,此代码以某种方式创建了访问冲突。我可以在不向用户显示控制台的情况下执行 mspaint 吗?

非常感谢。

最佳答案

第二个参数是 LPTSTR,即指向非常量字符数组的指针。 docs具体来说:

this parameter cannot be a pointer to read-only memory (such as a const variable or a literal string)

传递字符串文字的原因是有问题的:

The system adds a terminating null character to the command-line string to separate the file name from the arguments. This divides the original string into two strings for internal processing.

这意味着在您的情况下,它会尝试修改只读内存,因此会发生崩溃。

关于CreateProcess() 因访问冲突而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11339186/

相关文章:

android - Android 上的 GStreamer

c++ - 相当于 C++ 标准库模板 (STL) 中的 CreateProcess()

c++ - 我怎样才能产生一个只在给定时间内存在的进程

c++ - Windows Socket 无法绑定(bind) VPN IP 地址

c - 使用数组做一个自习室预约程序

c++ - 插入加密U盘后,如何使用WMI找到 'launcher'逻辑盘?

c - 调用时绘制

c++ - WinAPI SetSystemCursor 和 LoadCursorFrom - 如何设置默认光标?

c++ - 在 WIN32 上结合 CreateProcess 和 AllowSetForegroundWindow

c++ - 如何监视哪些进程访问 Unix 中的特定文件?