Mac OS X equivalent to CreateEvent () with a named object for interprocess communication?

I'm looking for the easiest or most suitable way for Mac OS X to simply β€œsignal” or notify one process from another. Based on the background of Windows, this can be achieved using the following.

In process A:

// create named event hCreatedEvent = CreateEvent(NULL, TRUE, FALSE, "MyUniqueNamedEvent"); // wait for it to be signalled WaitForSingleObject(hCreatedEvent, INFINITE); 

and then in process B:

 // open the existing named event hOpenedEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, "MyUniqueNamedEvent"); // signal it SetEvent(hOpenedEvent); 

So, when a SetEvent call is SetEvent in process B, process A breaks out of WaitForSingleObject and does some work.

I don't need to send any data, so I excluded things like Named Pipes (FIFO) or sockets, etc., as a bit of a brute force (I looked at this similar question , but since they should send data, my question is somewhat is different). Equally, I will not know the PID of another process (therefore, I need some kind of common object), so I cannot use anything that requires this.

While in my list there are:

  • POSIX sem_open - using sem_open , sem_wait and sem_post to create / open, wait, and signal events, respectively. Appears pretty good to use.
  • BSD notify(3) functions - seem pretty easy to use, if not a bit clumsy, to consume notifications.
  • The NSDistributedNotificationCenter or CFNotificationCenter are the most β€œMac-like way,” and it's pretty easy to do. However, my code may need to work as dylib and in accordance with this unanswered question , which may not work for me.

So, does anyone have any tips / advice / horror stories that have used any of the above or even more suitable alternatives that I did not think about in order to achieve what I want?

+6
source share
1 answer

So, after a bit more digging, I finally decided to go down the POSIX semaphore route, which seems to work for me, for example:

In process A (waiting on semaphore):

 // create semaphore, fail if already exists sem_t *sem = sem_open("MyUniqueSemaphore", O_CREAT | O_EXCL, 0666, 0); if (sem != SEM_FAILED) { // wait on semaphore if (sem_wait(sem) == 0) { // semaphore signalled! } // close our "handle" to the semaphore and remove it from the system sem_close(sem); sem_unlink("MyUniqueSemaphore"); } 

Then in process B (signaling a semaphore):

 // open the existing semaphore created in process A sem_t *sem = sem_open("MyUniqueSemaphore", 0); if (sem != SEM_FAILED) { // "signal" it sem_post(sem); // close our "handle" to the semaphore sem_close(sem); } 

The semaphore also seems to be a type of "auto reset" (in the Windows language), so it returns to unsignalled after passing it.

+4
source

Source: https://habr.com/ru/post/906146/


All Articles