如何同步两个进程?

hum*_*uru 6 hardware synchronization pthreads process named-pipes

我想在同一工作站上的两个应用程序(进程)中使用一个HW接口.HW需要单个初始化调用,然后应用程序使用相同的函数(在同一个库中)与HW进行许多事务.

所以每个应用程序都应该这样:

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)
Run Code Online (Sandbox Code Playgroud)

我可以在两个应用程序之间共享的锁定和引用计数调用中使用什么机制?我在想命名管道,即mkfifo().

alb*_*rtb 9

POSIX信号量是要走的路.由于您希望跨进程共享相同的信号量,因此您需要使用命名信号量:

命名信号量由表单/ somename的名称标识.通过将相同的名称传递给sem_open(3),两个进程可以对同一个命名信号量进行操作.