首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么未命名的信号量在共享内存中使用时不会改变?

为什么未命名的信号量在共享内存中使用时不会改变?
EN

Stack Overflow用户
提问于 2013-11-29 03:03:36
回答 1查看 759关注 0票数 1

我必须使两个进程(服务器/客户端)能够访问相同的共享内存。我通过服务器和客户端之间的UNIX套接字发送共享内存的密钥。然后,创建共享内存段,并使用未命名的信号量来同步服务器/客户端。正如我所想的,我做的一切都是正确的,但是当我运行客户机进程时,我可以看到信号量甚至没有初始化!

server.c样本:

代码语言:javascript
复制
#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样本:

代码语言:javascript
复制
#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连接没有什么问题,因为我共享和其他内存段,它们工作得很好。我还试图更改pshared参数的sem_init,但客户端仍然没有任何变化。实际上,我想在clinet的线程(M)中使用信号量,但我看到即使在主进程中,它们也不会初始化。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-29 16:56:12

(从注释中的故障排除.)

未初始化的key_t key3恰好被初始化为IPC_PRIVATE值,这意味着为shmget()的每个调用方创建了一个新的共享内存段。键应该显式初始化(在本例中是通过ftok())。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20277722

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档