CreateProcess出现未处理的错误

Unhandled Error with CreateProcess

本文关键字:错误 未处理 CreateProcess      更新时间:2023-10-16

我读到了c++中的CreateProcess函数,我想尝试一下。代码的基本思想是让我的main执行另一个进程(记事本)。真的,这只是基本的代码。当我运行程序时,我得到:

createprocess.exe中0x752bb763处的首次机会异常:0xC0000005:写入位置0x00be57b8的访问冲突。
createprocess.exe中0x752bb763处未处理的异常:0xC0000005:写入位置0x00be57b8的访问冲突。

当我确定错误发生的位置时,我会被带到tidtable.c(我想这是用于访问线程的)。具体在CRTIMP PFLS_GETVALUE_FUNCTION __cdecl __set_flsgetvalue()的tidtable.c中我真的不知道该如何避免这个问题。该错误发生在CreateProcess调用中(即,它从不输出"out of create")。

我的代码是:

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <strsafe.h>
#include <direct.h>
#include <string.h>
#include <conio.h>
int main(VOID)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
        //allocate memory
    ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));

fprintf(stderr, "This is just a test");
//create child process
if (!CreateProcess(NULL,
    L"C:\Windows\Notepad.exe",
    NULL,
    NULL,
    FALSE,
    0,
    NULL,
    NULL,
    &si,
    &pi))
{
        fprintf(stderr, "create process failed");
        return -1;
}
fprintf(stderr, "out of create");
    //parent waits for child to complete
WaitForSingleObject(pi.hProcess, INFINITE);
fprintf(stderr, "after wait");
printf("Child Complete");
    //close handle
CloseHandle(pi.hProcess);
//  CloseHandle(pi.hthread);
}

如果有人知道如何克服这个问题,我们将不胜感激。

问题是CreateProcess函数的第二个参数是输入/输出参数。

如果像以前那样将其指定为字符串,则它是一个常量字符串,并且调用它时函数无法写入内存位置,因此存在内存访问冲突。正确的方法是这样调用函数:

LPTSTR szCmdline = _tcsdup(TEXT("C:\Windows\Notepad.exe"));
//create child process
if (!CreateProcess(NULL,
    szCmdline,
    NULL,
    NULL,
    FALSE,
    0,
    NULL,
    NULL,
    &si,
    &pi))
{
    fprintf(stderr, "create process failed");
    return -1;
}

你可能还想看看这篇博客文章。

CreateProcess的第二个参数不能是const或文字字符串,因为func试图修改字符串。将文本复制到本地数组,然后将其作为第二个参数传递。