I’m trying to use WinApi to CreateFileMapping, MapViewOfFile and CopyMemory. It’s not showhing me errors and buffor is being filed with my PID
int write_pid_to_memory(const char *t_pid)
{
_tprintf(TEXT("[write_pid_to_memory] t_pid: (%s).n"), t_pid);
HANDLE h_map_file;
LPCTSTR p_buf;
h_map_file = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
BUF_SIZE, // maximum object size (low-order DWORD)
t_name); // name of mapping object
if (h_map_file == NULL)
{
_tprintf(TEXT("[write_pid_to_memory] Could not create file mapping object (%d).n"),
GetLastError());
return 1;
}
p_buf = (LPTSTR)MapViewOfFile(
h_map_file, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (p_buf == NULL)
{
_tprintf(TEXT("[write_pid_to_memory] Could not map view of file (%d).n"),
GetLastError());
CloseHandle(h_map_file);
return 1;
}
std::cout << "[write_pid_to_memory] strlen(t_pid) * sizeof(char) " << strlen(t_pid) * sizeof(char) << std::endl;
CopyMemory((PVOID)p_buf, t_pid, (strlen(t_pid) * sizeof(char)));
_getch();
std::cout << "p_buf " << p_buf << std::endl;
UnmapViewOfFile(p_buf);
CloseHandle(h_map_file);
return 0;
}
… but then there is reading from memmory
int access_pid_from_memory()
{
HANDLE h_map_file;
LPCTSTR p_buf;
h_map_file = OpenFileMapping(
FILE_MAP_ALL_ACCESS, // read/write access
FALSE, // do not inherit the name
t_name); // name of mapping object
if (h_map_file == NULL)
{
_tprintf(TEXT("[access_pid_from_memory] Could not open file mapping object (%d).n"),
GetLastError());
return 1;
}
p_buf = (LPTSTR)MapViewOfFile(
h_map_file, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
BUF_SIZE);
if (p_buf == NULL)
{
_tprintf(TEXT("[access_pid_from_memory] Could not map view of file (%d).n"),
GetLastError());
CloseHandle(h_map_file);
return 1;
}
MessageBox(NULL, p_buf, TEXT("[access_pid_from_memory] Process2"), MB_OK);
UnmapViewOfFile(p_buf);
CloseHandle(h_map_file);
return 0;
}
where I get System Error (2) while trying to open Mapping.
My PID: 19516
[access_pid_from_memory] Could not open file mapping object (2).
[write_pid_to_memory] t_pid: (19516).
[write_pid_to_memory] strlen(t_pid) * sizeof(char) 5
p_buf 19516
Envariamental variable = NEW
Env var value length = 3
Env var value compare resault = 0
Mutex created sucesfully
Code of those functions is from
https://learn.microsoft.com/en-us/windows/win32/memory/creating-named-shared-memory
and only thing I’ve changed is
CopyMemory((PVOID)p_buf, t_pid, (strlen(t_pid) * sizeof(char)));
Instead of
CopyMemory((PVOID)pBuf, szMsg, (_tcslen(szMsg) * sizeof(TCHAR)));
Where t_pid is just a const char *, becouse I was tired of Windows TCHAR types and I had no clue how to convert DWORD ProcessID to TCHAR to pass it to memcopy.
Well, I’m clueless why I’m unable to open Mapping. Windows is probably beyond me and I have no idea
how
TCHAR t_name[] = TEXT("Global\MyFileMappingObject");
is supposed to be recognised by system to find memory from which I want to read a message.
Whole programm is supposed to lock execution for only one process and if there is a System variable named «SO2» of value «NEW», new process should stop execution of previous process and continoue locking program for himself.
Locking mechanism is with mutex and to find previous porcess ID, I wanted my current process ID to be saved in memory, for next process to read it form, to close it when sys var will be «NEW».
Nothing crazy. All of this in Linux I’ve done in one day, but Windows is killing me.
Please help
There is main if someone would be intrested:
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <windows.h>
#include <string>
#include <conio.h>
#include <tchar.h>
#define BUFFER_SIZE 2048
#define ENV_KEY "SO2"
#define ENV_VAL "NEW"
#define BUF_SIZE 256
TCHAR t_name[] = TEXT("Global\MyFileMappingObject");
HANDLE h_mutex;
int write_pid_to_memory(const char *dw_pid);
int access_pid_from_memory();
int main(int argc, char **argv)
{
DWORD dw_pid = GetCurrentProcessId();
std::stringstream stream;
stream << dw_pid;
const char *t_pid = stream.str().c_str();
// int legnth = s_pid.length()
// const char *t_pid = (char*)malloc( * sizeof(char));
// const char t_pid = (char)malloc(strlen(dw_pid) * sizeof(char));
std::cout << "My PID: " << dw_pid << std::endl;
access_pid_from_memory();
write_pid_to_memory(t_pid);
std::string env_val(ENV_VAL);
char c_buffer[BUFFER_SIZE];
LPCSTR lp_name = ENV_KEY;
LPSTR lp_buffer = c_buffer;
DWORD dw_size = BUFFER_SIZE;
DWORD get_env_var;
//Write to memory your pid for other process to access it and close you
get_env_var = GetEnvironmentVariable(
lp_name,
lp_buffer,
dw_size);
if (GetLastError() == ERROR_ENVVAR_NOT_FOUND)
{
std::cout << "Couldn't find envariamental variable "SO2"." << std::endl;
}
if (BUFFER_SIZE == get_env_var)
{
std::cout << "Buffer for function [GetEnvironmentVariable] is too small. Function failed." << std::endl;
}
std::cout << "Envariamental variable = " << lp_buffer << std::endl;
std::string str_buffer(lp_buffer);
std::cout << "Env var value length = " << str_buffer.length() << std::endl;
std::cout << "Env var value compare resault = " << str_buffer.compare(env_val) << std::endl;
HANDLE h_mutex = NULL;
LPCSTR str = ENV_KEY;
h_mutex = OpenMutex(
MUTEX_ALL_ACCESS,
TRUE,
str);
if (NULL != h_mutex)
{
if (str_buffer.compare(env_val) == 0)
{
//Realease mutex3
ReleaseMutex(h_mutex);
//Close previous process
}
else
{
throw std::runtime_error("Instance of a program is already running");
}
}
h_mutex = CreateMutex(
NULL,
FALSE,
str);
if (h_mutex == NULL)
{
std::cout << "Failed to create mutex: error - " << GetLastError() << std::endl;
return 1;
}
std::cout << "Mutex created sucesfully" << std::endl;
DWORD dw_wait_res;
dw_wait_res = WaitForSingleObject(
h_mutex, // handle to mutex
INFINITE); // no time-out interval
for (;;)
{
Sleep(100);
}
CloseHandle(h_mutex);
system("PAUSE");
return 0;
}
← →
__max__
(2005-02-10 10:37)
[0]
Имеется некое приложение и некая библиотека. Сначала библиотека делает так:
HANDLE hMap = NULL;
hMap = CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024, «MyMapName»); // возвращает описатель, все нормально здесь ошибки не будет
Потом некое приложение делает так:
HANDLE hMap = NULL;
TCHAR s[50];
hMap = OpenFileMapping (FILE_MAP_ALL_ACCESS, TRUE, «MyMapName»); // вот здесь возвращается NULL
sprintf(s, «ERROR #%d», GetLastError());
MessageBox(0, s, «Error!», 16);
Выдается ошибка #2 => Не удается найти указанный файл. Почему??? (SP2, MSVC++.NET)
← →
Alexander Panov ©
(2005-02-10 10:39)
[1]
А почему ты думаешь, что для приложения, который выполняет OpenFileMapping текущий каталог тот же, что и для первого?
← →
__max__
(2005-02-10 10:55)
[2]
Alexander Panov © (10.02.05 10:39) [1]
Я поставил SetCurrentDirectory(«c:\»); перед CreateFileMapping в библиотеке, и перед OpenFileMapping в приложении, результата не дало А вообще я незнал что в данном случае надо учитывать текущие каталоги, я думал для таких «проецируемых файлов» есть специальный каталог определенный Windows.
← →
Digitman ©
(2005-02-10 11:37)
[3]
> Alexander Panov © (10.02.05 10:39) [1]
насчет тек.каталога это ты загнул ..
> __max__
странно .. вроде бы явных предпосылок к отказу из приведенного кода не видно ..
а может первый процесс у тебя завершается еще ДО того как второй пытается открыть MMF ?
и, кстати, чем обоснован 2-й параметр = True ?
← →
Alexander Panov ©
(2005-02-10 11:42)
[4]
Digitman © (10.02.05 11:37) [3]
насчет тек.каталога это ты загнул ..
Это точно, загнул.
Код автора вопроса у меня работает без изменений без ошибок.
Но у меня W2000, и пользователь — администратор
← →
__max__
(2005-02-10 11:56)
[5]
Digitman © (10.02.05 11:37) [3]
> странно .. вроде бы явных предпосылок к отказу из приведенного
> кода не видно ..
>
> а может первый процесс у тебя завершается еще ДО того как
> второй пытается открыть MMF ?
Ну да так и есть, а чего от этого зависит да? А как тогда быть?
← →
__max__
(2005-02-10 11:56)
[6]
Digitman © (10.02.05 11:37) [3]
> странно .. вроде бы явных предпосылок к отказу из приведенного
> кода не видно ..
>
> а может первый процесс у тебя завершается еще ДО того как
> второй пытается открыть MMF ?
Ну да так и есть, а чего от этого зависит да? А как тогда быть?
← →
Alexander Panov ©
(2005-02-10 11:59)
[7]
__max__ (10.02.05 11:56) [6]
Ну да так и есть, а чего от этого зависит да? А как тогда быть?
Первый процесс должен ждать, пока не отработает второй. Только и всего.
← →
Digitman ©
(2005-02-10 12:24)
[8]
> __max__
что значит «Ну да так и есть» ?
в случаях если ИЛИ
— 1-й процесс, создавший MMF, завершается раньше чем 2-й процесс попытается открыть MMF
ИЛИ
— 1-й процесс, создавший MMF, завершается НЕ раньше чем 2-й процесс попытается открыть MMF, но явно уничтожит MMF-объект раньше чем 2-й процесс попытается открыть этот MMF
тебе обеспечен именно тот геморрой, который ты сейчас схлопотал
← →
__max__
(2005-02-10 15:02)
[9]
> Alexander Panov © (10.02.05 11:59) [7]
> Первый процесс должен ждать, пока не отработает второй.
> Только и всего.
Что значит только и всего? У меня первый процесс — это библиотека. Выгрузка этой библиотеки происходит только тогда когда прорцесс к которому она прицепилась(хук короче) будет закрыт. В момент выгрузки (DLL_PROCESS_DETACH) происходит создание проекции файлаHANDLE hMap = NULL;
hMap = CreateFileMapping (INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, SomeSize, "MyMapName"); // возвращает описатель, все нормально здесь ошибки не будет
Потом выполняется MapViewOfFile, копируется в эту проекцию некая строка размер которой может быть совершенно разным (KEYBOARD HOOK)
Процесс второй — это мое клиентское приложение которое ждет пока не завершиться процесс 1(то-есть процесс в который загружениа библиотека). Приложение как только узнав что процесс 1 был завершен, выполняет следующее:hMap = OpenFileMapping (FILE_MAP_ALL_ACCESS, TRUE, "MyMapName"); // вот здесь возвращается NULL
sprintf(s, "ERROR #%d", GetLastError());
MessageBox(0, s, "Error!", 16);
Но теперь я понял свою ошибку — процесс 1 как только завершается закрывает все хэндлы. Но как мне тогда быть, если мне нужно узнать строку которую я спроецировал? Конечно можно просто создавать промежуточные файлы, но это IMHO не очень красивая реализация. У вас есть какие-либо идеи по поводу данной проблемы
← →
Владислав ©
(2005-02-10 15:14)
[10]
SendMessage и WM_COPYDATA не спасут?
← →
Digitman ©
(2005-02-10 15:21)
[11]
> Но теперь я понял свою ошибку — процесс 1 как только завершается
> закрывает все хэндлы
уфф… аминь ! …
> Но как мне тогда быть, если мне нужно узнать строку которую
> я спроецировал?
между прочим, MMF-механизм был придуман хотя бы для интерпроцессного взаимодействия в части использования разделяемых несколькими процессами одновременно ресурсов памяти … и о каком же интерпроцессном взаимодействии может идти речь, когда у тебя в каждый момент времени существует всего один заинтересованный в ресурсе процесс ?
Troubleshooting
Problem
This technote explains why attempts to describe or perform any action in an IBM® Rational® ClearCase® VOB results in the errors: *** db_VISTA error 2 from OpenFileMapping() of lockmgr_almd *** db_VISTA database error -920 — no lock manager is installed.
Cause
This error occurs when a ClearCase VOB database server process (vob_server, vobrpc_server, or db_server) can not contact the lock manager.
The most common reasons for this problem are:
- Lock manager no longer running
- ClearCase is in the process of being shutdown (most common reason as lockmgr.exe is terminated before albd_server.exe)
- Lock manager is misconfigured.
- Possibly left out or misconfigured the -a almd line
For example:
If the command line reads:a almd -f 1018 -u 1050 -q 5080
instead of
-a almd -f 1018 -u 1050 -q 5080
(where the dash is missing before the a option) the lock manager will not be listening on the correct port.
- The lock manager process itself might not be running. To determine this, do one of the following:
Microsoft® Windows®:
Open the Windows Task Manager > Processes tab > click on the Image Name column, and look for lockmgr.exeUNIX®:
Open a command prompt and type the following command:
ps -aef | grep «lockmgr»
For more information on Lock manager tuning options, review the ClearCase Administrator’s Guide.
Resolving The Problem
- Verify that the lock manager is running and is properly configured.
To verify that the Lock manager process is running, run the following command:
Windows:
net start | find /i «lock»
Note:
If you are running ClearCase 2003.06 or later, you should see a line reading «Rational Lock Manager». If you are running ClearCase 2002.05, you should see a line reading «Atria Lock Manager.»
Example:
C:>net start | find /i «lock»
Rational Lock ManagerUNIX:
ps -ef |grep lockmgrExample:
> ps -ef |grep lockmgr
root 199 1 0 Apr 29 ? 0:00 /opt/rational/clearcase/etc/lockmgr -a /var/adm/rational/clearcase/almd -q 1024 - Verify the lock manager is configured properly. Review technote 1125258 for more information.
Related Information
[{«Product»:{«code»:»SSSH27″,»label»:»Rational ClearCase»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»Database»,»Platform»:[{«code»:»PF002″,»label»:»AIX»},{«code»:»PF010″,»label»:»HP-UX»},{«code»:»PF016″,»label»:»Linux»},{«code»:»PF027″,»label»:»Solaris»},{«code»:»PF033″,»label»:»Windows»}],»Version»:»7.0″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}},{«Product»:{«code»:»SSSH27″,»label»:»Rational ClearCase»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»Database»,»Platform»:[{«code»:»»,»label»:»»}],»Version»:»»,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]
|
|
|
Правила раздела Visual C++ / MFC / WTL (далее Раздела)
Глючит OpenFileMapping
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Senior Member Рейтинг (т): 8 |
hfileMap = :: CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(HWND), szHandle); Работает и в Win98 и в WinXP hfileMap = :: OpenFileMapping(FILE_MAP_WRITE | FILE_MAP_READ, FALSE, szHandle); Работает в Win98 , в WinXP возвращает NULL . В чём прикол ??? ??? Сообщение отредактировано: Gurza — 17.05.02, 05:54 |
zAg |
|
А GetLastError какой? Наверняка access denied, тк открываешь на полный доступ. Особенно если взаимодействуют процессы под разными аккаунтами. Погляди какие у объекта получаются параметры безопасности. |
Gurza |
|
Senior Member Рейтинг (т): 8 |
GetLastError() == 2; т.е. —> «The system cannot find the file specified» Может кто подскажет как конкретно вылечить эту проблему. |
zAg |
|
Такая ошибка говорит о том, что у тебя по каким-то причинам не совпадают szHandle. |
Gurza |
|
Senior Member Рейтинг (т): 8 |
Разобрался. Я после hfileMap = :: CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(HWND), szHandle); Ну и соответственно NULL == :: OpenFileMapping(FILE_MAP_WRITE | FILE_MAP_READ, FALSE, szHandle); |
Gurza |
|
Senior Member Рейтинг (т): 8 |
Как она в Win98 работала ??? (хотя правда через раз ;D) |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Visual C++ / MFC / WTL
- Следующая тема
[ Script execution time: 0,0268 ] [ 16 queries used ] [ Generated: 9.02.23, 22:37 GMT ]