【问题标题】:Shared mutex between process进程间共享互斥锁
【发布时间】:2021-10-10 17:53:20
【问题描述】:

我正在学习进程之间的互斥锁用法。我有一个问题。

由于每个进程都有自己的地址空间,一个进程定义的互斥锁不能被另一个进程看到。在谷歌搜索时,我发现使用 pthread_mutex_setpshared() 来完成这项工作。我在下面附上我的代码。但看起来即使是现在,互斥锁也没有在进程之间共享。这个要怎么修改。

我知道这可以使用命名信号量来实现。但是想知道互斥量的用法。

#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
#include <semaphore.h>
#include <fcntl.h>

int main()
{
    pid_t pid;
    int ch = 0;
    //sem_t *s1;
    //s1 = sem_open("/sem", O_CREAT, 0666, 0);
    pthread_mutex_t m1;
    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
    pthread_mutex_init(&m1, &attr);
    
    
    pid = fork();
    
    if(pid == 0)
    {
        pthread_mutex_lock(&m1);
        printf("\nChild process");
        
        printf("\nPress 1 to unlock from child:");
        scanf("%d", &ch);
        
        if(ch == 1)
        {
            pthread_mutex_unlock(&m1);
        }
        //sem_post(s1);
    }
    else if (pid > 0)
    {
        pthread_mutex_lock(&m1);
        //sem_wait(s1);
        printf("\nParent process");
        
        printf("\nPress 2 to unlock from parent:");
        scanf("%d", &ch);
        
        if(ch == 2)
        {
            pthread_mutex_unlock(&m1);
        }
    }
    else
    {
        
        printf("\nError");
    }
    
}

【问题讨论】:

    标签: process operating-system pthreads ipc mutex


    【解决方案1】:

    除了设置PTHREAD_PROCESS_SHARED 属性外,您还需要安排将互斥锁本身(您的m1 变量)存储在共享内存中,供两个进程访问。由您的 fork() 创建的副本不起作用。

    如果您使用mmap() 使用MAP_SHARED 标志创建一个匿名映射,并在其中分配互斥锁,那么它将在fork() 之后的进程之间共享并且可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2013-11-24
      • 2021-07-28
      • 2017-07-26
      • 2013-12-17
      • 1970-01-01
      相关资源
      最近更新 更多