How to use named mutex and shared memory between a windows service and a process?

自闭症网瘾萝莉.ら 提交于 2019-12-11 10:35:45

问题


I'm have a code written in C++\MFC that is run as a Windows Service and a (normal) C++\MFC Windows process - now I wish to communicate between the two using named Mutex and Shared memory (File mapping).

How is that possible ?


回答1:


It depends on your communication requirements. Generally the service creates the mutex and shared memory and the clients open them and do stuff. OutputDebugString() is a classic example of IPC using a mutex and shared memory (and some events). Here is a detailed examination of how OutputDebugString() works; you could do something similar.




回答2:


I suggest the following

  1. service creates a mutex, 2 events and a memory mapped file(m.m.f), all named

  2. when the service has to send data to the other process

    a. takes ownership of the mutex

    b. writes data to m.m.f.

    c. signals event#1 which means that the service has new information for the program

    d. releases the mutex

  3. when the program want to send data to the service

    a. takes ownership of the mutex

    b. writes data to m.m.f.

    c. signals event#2 which means that the program has new info for the service

    d. releases the mutex

  4. the service checks to see if event#2 is on. If not goes on doing its stuff, else it:

    a. takes ownership of the m.m.f

    b. reads data

    c. resets event#2

    d. releases mutex

  5. the program checks to see if event#1 is on. If not goes on doing its stuff, else it:

    a. takes ownership of the m.m.f

    b. reads data

    c. resets event#1

    d. releases mutext

The problem with this approach is that messages could be lost (when for example the service manages to write 2 messages in a row, before the program can read the first) AND only 1 process can attach itself to the service (you have to make sure about it)

I suggest a socket based solution, if that is possible, where neighter of these problems occur.

P.S. you can use the m.m.f to make some kind of queue to avoid the first problem



来源:https://stackoverflow.com/questions/3747055/how-to-use-named-mutex-and-shared-memory-between-a-windows-service-and-a-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!