Reputation:
I have ParentProcess.exe which has the following code. It creates a file and fils it with a simple character of 1 then it creates a new process which is called ChildProcess.exe. This ChildProcess created with bIheritance flag true. I wanted it to have the ability to get access to the objects of the parent.
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
int main(int argc, const char* argv[])
{
SECURITY_ATTRIBUTES process_sa;
process_sa.nLength = sizeof(process_sa);
process_sa.bInheritHandle = TRUE;
process_sa.lpSecurityDescriptor = 0;
SECURITY_ATTRIBUTES thread_sa;
thread_sa.nLength = sizeof(thread_sa);
thread_sa.bInheritHandle = TRUE;
thread_sa.lpSecurityDescriptor = NULL;
HANDLE hFileCreated = CreateFile("e:\\Sample.txt", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, &process_sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hFileCreated == INVALID_HANDLE_VALUE)
{
printf("File doesn't created.");
return 1;
}
char c = '1';
DWORD w;
WriteFile(hFileCreated, &c, 1, &w, 0);
STARTUPINFO sinfo;
ZeroMemory(&sinfo, sizeof(sinfo));
sinfo.cb = sizeof(sinfo);
PROCESS_INFORMATION pinfo;
ZeroMemory(&pinfo, sizeof(pinfo));
if (CreateProcess(0, "ChildProcess.exe", &process_sa, &thread_sa, TRUE, 0, 0, 0, &sinfo, &pinfo))
printf("done.");
else
printf("failed.");
CloseHandle(pinfo.hThread);
CloseHandle(pinfo.hProcess);
return 0;
}
ChildProcess.exe had the following code which I wanted it can get access to the handle of the file which is created by the parent process but when it gets run it shows the address of 0XFFFFFFFF. Where is the problem. The ChildProcess code:
#include <Windows.h>
#include <process.h>
#include <stdio.h>
#include <tchar.h>
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE hFileCreatedInheritance = INVALID_HANDLE_VALUE;
_stscanf_s(L"e:\\Sample.txt", _T("%p"), &hFileCreatedInheritance);
printf("The handle of the file is %p.\n", hFileCreatedInheritance);
return 0;
}
Upvotes: 0
Views: 148
Reputation: 1368
In parent process:
Convert your handle to a string before inserting it into the text file:
DWORD w;
std::stringstream streamAdr;
streamAdr << hFileCreated;
std::string strAddr = streamAdr.str();
WriteFile(hFileCreated, strAddr.c_str(), strAddr.size(), &w, 0);
In child process:
string sLine;
ifstream infile("G:\\Sample.txt");
if (infile.good())
{
getline(infile, sLine); // Get first line containing handle of file
infile.close();
unsigned int i = stoi(sLine.c_str(), 0, 16); // Convert hexadecimal string
hFileCreatedInheritance = (HANDLE) i; // cast to a HANDLE
printf("The handle of the file is %p.\n", hFileCreatedInheritance);
}
Result:
Question:
what are you trying to achieve?
Upvotes: 0