无法读取继承进程中的文件

Can't read file in inherited process

本文关键字:文件 进程 继承 读取      更新时间:2023-10-16

我正在尝试在继承进程中读取文件,我通过命令行传递的文件句柄有效,但GetFileSize(HANDLE,LPDWORD)返回0

#include"mainClass.h"
MainClass* MainClass::ptr = NULL;
MainClass::MainClass()
{
    ptr = this;
}
BOOL CALLBACK MainClass::DlgProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg)
    {
        HANDLE_MSG(hwnd,WM_CLOSE,ptr->OnClose);
        HANDLE_MSG(hwnd,WM_COMMAND,ptr->OnCommand);
        HANDLE_MSG(hwnd,WM_INITDIALOG,ptr->OnInitDialog);
    }
    return false;
}
BOOL MainClass::OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
    SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES),0,true};
    hFile = CreateFile(_T("D:/mutex.txt"),GENERIC_READ,0,&sa,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
    return true;
}
void MainClass::OnClose(HWND hwnd)
{
    DestroyWindow(hwnd);
    PostQuitMessage(0);
}
void MainClass::OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
    if(codeNotify == BN_CLICKED)
    {
        if(id == IDC_BUTTON_READ_ENCRYPT)
        {
            TCHAR* cmd = new TCHAR[100];
            _stprintf(cmd,_T("readFromFile.exe %d"),(int)hFile);
            STARTUPINFO si = {sizeof(STARTUPINFO)};
            PROCESS_INFORMATION pi = {0};
            if(CreateProcess(NULL,cmd,NULL,NULL,true,NULL,NULL,NULL,&si,&pi))
            {
                //CloseHandle(hFile);
                //CloseHandle(pi.hThread);
                //CloseHandle(pi.hProcess);
            }
            delete[]cmd;
        }
    }
}

继承过程是控制台应用程序:

#include<windows.h>
#include<stdio.h>
#include<conio.h>
#include<tchar.h>
PTSTR buf;
HANDLE hFile;
void main()
{
    int s = 100;
    buf = new TCHAR[s];
    TCHAR* temp = buf;
    _tcscpy(buf,GetCommandLine());
    while(*buf++ != _T(' '));
    hFile = (HANDLE)_ttoi(buf); 
    _tprintf(_T("%dn"),(int)hFile);
    getch();
    buf = temp;
    delete[]buf;
    if(hFile == INVALID_HANDLE_VALUE)
    {
        MessageBox(NULL,_T("file handle invalid"),_T("Error"),NULL);
        return;
    }
    DWORD fileSize;
    GetFileSize(hFile,&fileSize);
    _tprintf(_T("%dn"),(int)fileSize);
    getch();
    if(!fileSize)
    {
        MessageBox(NULL,_T("file is empty"),_T(""),NULL);
        return;
    }
    buf = new TCHAR[fileSize/sizeof(TCHAR)+1];
    DWORD wasRead;
    ReadFile(hFile,buf,fileSize,&wasRead,NULL);
    _tprintf(buf);
    if(buf)
        delete[]buf;
    getch();
}

这里有什么问题,请帮助:)。

GetFileSize需要处理大于 4GB 的文件,因此它应该能够处理long longint64_t但在 Windows API 中int64_t通常用于 32 位整数值,因此此函数返回低阶 32 位结果作为返回值,并且在第二个参数中只有高 32 位结果,并且您的文件小于 4GB, 所以它的高阶 32 位总是 0。所以使用fileSize = GetFileSize(hFile, NULL),一切都按预期工作