问题
To work with databases or files as simple data persistance layer is easy to understand. But there are also ways to use them as communication channel to transfer data from one running process to another one or even send commands and requests, especially when this channel is faster then normal Unix sockets, like shared memory.
But how do you use this efficiently? I mean, a process doesn't get an Event for a change in shared memory, he always has to poll for it, right? But isn't that too resource intensive if all the processes are polling their shared memory all the time? What other alternatives are there?
回答1:
To get notification of a change using IPCs on a Unix or Linux system, I could think of different technique without resorting to polling.
1st Blocking Read
One could use a file descriptor (a file, a Unix socket, a pipe or named pipe, an IPC queue, etc.). The consumer will read this file in a blocking way (a timeout is perhaps advised). The producer will write something to this file descriptor once it has updated the shared memory. Thus the consumer would get awaken from the read when this happen and go read the shared memory. The consumer will be in sleep state, so not consuming resources (like CPU) while waiting.
One could even use select
for the consumer to wait for several file descriptor at the same time.
2nd Signals
The consumer would be awaken by a signal sent by the producer. The producer sends a signal (SIGUSR1 for instance) to the consumer once it has updated the shared memory. The consumer had subscribed previously to the signal and can handle the request. It is a bit more complex to handle because the even can be triggered at any time, so the design of the consumer is more difficult.
回答2:
Files and databases were designed for storing data and using them for IPC is possible only as a helper, where other mechanisms (mutex, events, semaphores and alike) are used for synchronizing access to data and signaling about changes. These mechanisms are being "listened to" and it's not resource-consuming to wait for such signal. On the other hand reading the file trying to catch changes (this applies to memory-mapped files or shared memory) is both resource-wasteful and can cause troubles if you don't synchronize read and write access (which brings you back to mutex and events etc.)
来源:https://stackoverflow.com/questions/10736396/softwaredevelopment-patterns-for-files-and-caches-as-inter-process-communication