我有一個父行程,它使用CreateFile()創建一個檔案并將其鎖定。下面是代碼:
m_hWriterLockFile = ::CreateFile("C:Test.txt" ,
generic_read | generic_write。
0, //exclusive.
NULL, //default security.
OPEN_ALWAYS,
file_attribute_normal,
NULL)。)
現在,我希望只有子行程能夠訪問這個鎖定的檔案。我不希望任何其他行程讀取這個檔案。
我已經創建了一個子行程。下面是示例代碼:
//初始化一個安全屬性結構。
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(SECURITY_ATTRIBUTES)。
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = TRUE。
if (!CreateProcess("FileReader.exe", // I want to invoke this exe)
"C:Test.txt"。
&sa。
NULL。
為真。
0,
NULL,
NULL。
&si,
&pi))
{
std::cout << "Create Process Faild (%d)" << GetLastError() << '
'。
不幸的是,我無法實作我的目標,有沒有人可以幫助我?是否有其他方法來實作這個目標?如果需要,我將分享更多的資訊(代碼)。
注意:我沒有分享完整的代碼以使文章更短。
uj5u.com熱心網友回復:
以下是我問題的答案:
用一個可繼承的句柄創建檔案,并將該句柄傳遞給子行程。一個簡單的方法是把它作為一個命令列引數來傳遞。我們必須向 CreateFile 傳遞一個 SECURITY_ATTRIBUTES 結構,指定 bInheritHandle 為 TRUE,同時向 CreateProcess 的呼叫的 bInheritHandles 引數傳遞 TRUE。
創建檔案
例子:
SECURITY_ATTRIBUTES sa{ sizeof sa, nullptr, TRUE };
HANDLE hFile = CreateFileA("C:Test.txt",
generic_read | generic_write。
0,
&sa,
CREATE_ALWAYS,
file_attribute_normal,
NULL)。)
子程序:
UINT_PTR uiHandle = reinterpret_cast<UINT_PTR>(hFile)。
sprintf_s(szCmdLine, " "%s" %Iu", szExePath, uiHandle);
if (CreateProcessA(nullptr,
szCmdLine,
nullptr,
nullptr,
為真。
create_new_console。
nullptr。
nullptr,
&si,
&pi))
{
CloseHandle(pi.hThread)。
CloseHandle(pi.hProcess)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/320300.html
標籤:
上一篇:為什么chrome/visualstudiocode/edge都有相同的類名"Chrome_WidgetWin_1"?
