【发布时间】: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