基于pthread_mutex的进程间通信无法正常工作

时间:2017-01-12 00:44:04

标签: c++ linux pthreads

我目前正在尝试使用pthread_mutex模型在Linux中同步两个进程。

以下是我正在处理的代码:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

using namespace std;

int main (int argc, char **argv)
{
    printf ("starting process\n");

    if (_POSIX_THREAD_PROCESS_SHARED == -1) {
        printf ("shared mutex is not supported!\r\n");
    }

    pthread_mutexattr_t attr;
    pthread_mutex_t shm_mutex;


    if (pthread_mutexattr_init(&attr) != 0)
        printf ("init attr error!\r\n");
    if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL) != 0)
        printf ("set type error!\r\n");
    if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED) != 0)
        printf ("set shared error!\r\n");

    int value;
    if (pthread_mutexattr_getpshared(&attr, &value) != 0 || value != PTHREAD_PROCESS_SHARED) {
        printf ("mutex is not shared!\r\n");
    }

    if (pthread_mutex_init(&shm_mutex, &attr) != 0)
        printf ("mutex init error!\r\n");

    for (int i=0; i < 10; i++) {

        if (pthread_mutex_lock(&shm_mutex) != 0)
            printf ("lock error!\r\n");

        printf ("begin run %d\r\n", i);
        sleep(10);
        printf ("end run %d\r\n", i);

        if (pthread_mutex_unlock(&shm_mutex) != 0)
            printf ("unlock error!\r\n");

        sleep(1); // sleep 1 second
    }

    pthread_mutex_destroy(&shm_mutex);
    pthread_mutexattr_destroy(&attr);

    return 0;
}

当我运行两个单独的进程时,开始/结束逻辑不起作用。

代码有什么问题吗?

1 个答案:

答案 0 :(得分:3)

您应该自己在共享内存中分配shm_mutex。见man shm_overview。该标志仅表示您允许使用互斥锁执行此操作。

有关详细信息,请参阅this reference