POSIX semaphores on iOS

Hi,

I found the following documentation addressing how to use POSIX semaphores for multiple apps in an app group.

https://developer.apple.com/library/archive/documentation/Security/Conceptual/AppSandboxDesignGuide/AppSandboxInDepth/AppSandboxInDepth.html#//apple_ref/doc/uid/TP40011183-CH3-SW24

It's not that clear that this is macOS only and I saw some blog posts where people got Mach ports running on iOS, so I speculated POSIX semaphores may also work and I tried it like this.

 
func doExternalHardwareInit() {

    var sema = sem_open("our.app.group/A", O_CREAT, 0o660, 1)

    guard sema != SEM_FAILED else {
        perror("sem_open")
        exit(EXIT_FAILURE)
    }

    defer { sem_close(sema) }

    print("Waiting for semaphore")
    sem_wait(sema) // stuck here
    print("Got semaphore")

    // run code that must not run multiple times

   sem_post(sema)
}

It seems that this is not working. It is stuck sem_wait(sema) even when only one of the app groups is executing this.

Is this intended not work on iOS?

Background:

We have a few apps in an app group that need to access a external hardware connected via ethernet to an iOS device.

There are certain initialisation tasks involving this hardware where we need to make sure that only one of the apps is talking to that hardware. We do that for example automatically when the app starts.

With iOS 15 came the pre heat start of apps and we recognised that our apps may run in parallel and are starting those initialisations at the same time.

But we also would like make sure that certain interactions with the hardware are finished carefully when the apps are switched.

Best Alex

I ran your code under macOS playground no issues. Just doesn't work under an iOS playground.

import Foundation



func doExternalHardwareInit() {
    let sema = sem_open("our.app.group/A", O_CREAT, 0o660, 1)
    defer { sem_close(sema) }
    guard sema != SEM_FAILED else {
        perror("sem_open")
        exit(EXIT_FAILURE)
    }
    print("Waiting for semaphore")
    sem_wait(sema) // stuck here
    print("Got semaphore")
    // run code that must not run multiple times
   sem_post(sema)
}
doExternalHardwareInit()
POSIX semaphores on iOS
 
 
Q