How to synchronize two processes

hardwarenamed-pipesprocesspthreadssynchronization

I have a single HW interface I want to use from two applications (processes) on the same workstation. The HW requires a single initialization call then either app uses the same function (in the same library) to do many transactions with the HW.

So each app should act like this:

main()
    // I don't know if another app already init'ed the HW
    ret = hw_init_lock(non-blocking)

    if ret = OK
        // no one else has done this, I have to
        init_hw()
    else
       //someone else has already init'ed the HW, I gotta make sure it stays that way
       //as long as I'm alive
       increment_hw_init_ref_counter()

    hw_trans_lock(blocking)
    hw_trans()
    hw_trans_unlock()
    ....

    //exit app, uninit hw if we are last out
    ret = decrement_hw_init_ref_counter()
    if ret == 0
        uninit_hw()

    exit(0)

What is the mechanism I can use in the lock and reference count calls that is shared between two applications? I'm thinking named pipes i.e. mkfifo().

Best Solution

POSIX semaphore is the way to go. Since you want to share the same semaphore across processes, you need to use a named semaphore.:

A named semaphore is identified by a name of the form /somename. Two processes can operate on the same named semaphore by passing the same name to sem_open(3).