![](/img/trans.png)
[英]Semaphore deadlock when using unnamed semaphores in POSIX with shared memory
[英]Why unnamed semaphore doesn't change when used in shared memory?
我必须使2个进程(服务器/客户端)可以访问相同的共享内存。 我通过服务器和客户端之间的UNIX套接字发送共享内存的密钥。 然后,创建共享内存段,并使用未命名的信号量同步服务器/客户端。 我认为,我做的所有事情都正确,但是当我运行客户端进程时,我可以看到信号量甚至还没有初始化!
server.c示例:
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <errno.h>
sem_t *semaphore;
int main(int argc, char **argv){
//...making the connections here
// M is the number of semaphores i will use
key_t key3;
int shmid3;
if ((shmid3 = shmget(key3, M*sizeof(sem_t), 0644 | IPC_CREAT)) == -1) {
perror("shmget3");
exit(1);
}
key3 = htonl(key3);
if (send(s2, (const char*)&key3, 4, 0) == -1) {
perror("send");
exit(1);
}
int i;
semaphore=(sem_t *)shmat(shmid3, (void *) 0, 0);
if (semaphore == (sem_t *)(-1)) perror("shmat");
for(i=0;i<M;i++) if(sem_init(&semaphore[i], 1, 1)!=0) perror("sem_init");
//..do some stuff...
sleep(3);
for(i=0;i<M;i++) sem_destroy( &semaphore[i] );
if (shmdt(semaphore) == -1) {
perror("shmdt");
exit(1);
}
shmctl(shmid3, IPC_RMID, NULL);
//close connection...
}
client.c示例:
#include <stdlib.h>
#include <stdio.h>
#include <semaphore.h>
#include <unistd.h>
#include <errno.h>
sem_t *semaphore;
int main(int argc, char **argv){
//...making the connections here
// M is the number of semaphores i will use
key_t key3;
n = recv(s, &key3, 4, 0);
if (n < 0) {
perror("recv");
}
key3 = ntohl(key3);
int shmid3;
if ((shmid3 = shmget(key3, M*sizeof(sem_t), 0644 )) == -1) {
perror("shmget3");
exit(1);
}
semaphore=(sem_t *)shmat(shmid3, (void *) 0, 0);
if (semaphore == (sem_t *)(-1)) perror("shmat");
int value;
sleep(1);
sem_getvalue(&semaphore[0], &value);
printf("\n[%d]\n",value); //always prints 0
//...do stuff...
if (shmdt(semaphore) == -1) {
perror("shmdt");
exit(1);
}
//close connection...
}
UNIX连接没有什么问题,因为我共享了内存段和其他内存段,并且它们工作得很好。 我也尝试更改sem_init
的pshared
参数,但是客户端中仍然没有任何更改。 我实际上想在clinet的threads(M)中使用信号量,但是我看到它们甚至在主进程中也没有初始化。
(适应于注释中的疑难解答...)
未初始化的key_t key3
恰好被初始化为key_t key3
值,这意味着将为每个shmget()调用者创建一个新的共享内存段。 该密钥应显式初始化(在本例中为ftok())。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.