[英]Copying Data from Shared memory segment causes seg fault in the client ( semaphores & shared memory)
我正在尝试编写一个简单的生产者和消费者程序(两个不相关的过程)。 ,具有共享的内存和信号灯。 我将信号量为空和满作为条件变量,并将数据从生产者存储到共享内存段中。 而且,我尝试将数据存储到使用者中的局部变量中,但这会导致段错误。 这很奇怪,我不知道发生了什么。 这是代码。
生产者和消费者的共同部分(信号量和共享内存创建):
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <string.h>
#include<stdlib.h>
#include <sys/shm.h>
struct a
{
int a;
int b;
}a_s;
void wait(int semid)
{
int err,nsops=1;
struct sembuf *sops = (struct sembuf *) malloc(sizeof(struct sembuf));
sops[0].sem_num = 0;
sops[0].sem_op = -1;
sops[0].sem_flg = 0;
err=semop(semid, sops, nsops);
if(err < 0)
printf(" unable to do the sop \n");
}
void signal(int semid)
{
int err,nsops=1;
struct sembuf *sops = (struct sembuf *) malloc(sizeof(struct sembuf));
sops[0].sem_num = 0;
sops[0].sem_op = 1;
sops[0].sem_flg = 0;
err=semop(semid, sops, nsops);
if(err < 0)
printf(" unable to do the sop \n");
}
int main()
{
int i, err;
int full,empty;
key_t full_key = 1234, empty_key = 5678;
int sem_flg = IPC_CREAT | 0666;
int nsems = 1;
int nsops = 2;
int shmid;
void *string;
void *s;
int shm_key = 9999;
struct a *a_str;
/*****************************************/
empty = semget(empty_key, nsems, sem_flg);
if(empty < 0)
printf(" failed to initialize the semaphore \n");
semctl(empty, 0, SETVAL, 1) ;
/****************************************/
full = semget(full_key, nsems, sem_flg);
if(full < 0)
printf(" failed to initialize the semaphore \n");
semctl(full, 0, SETVAL, 0) ;
/*****************************************/
shmid = shmget(shm_key, 30, IPC_CREAT|0666);
if(shmid < 0)
printf(" unable to create shmem \n");
else
printf(" created shm \n");
string = shmat( shmid, NULL, 0);
if( string == (void * ) (-1))
printf(" unable to attach the string \n");
else
printf(" success with shmat \n");
s = string;
/******************************************/
生产者:输入数据
while(1)
{
wait(empty);
sleep(1);
memcpy( string, (void *) a_str, sizeof(struct a));
printf(" wrote the string \n");
signal(full);
}
使用者:复制数据并显示
while(1)
{
wait(full);
printf(" after full \n");
memcpy((void *)a_str, (void *)s, sizeof(struct a));
printf(" copied the memory from string \n");
printf(" a %d b %d \n",((struct a *)a_str)->a, ((struct a *)a_str)->b);
sleep(1);
memcpy(s, string, 7);
signal(empty);
}
return 0;
}
有人可以让我知道为什么它的段错误吗? 我只是从内存段复制地址。 可能出什么问题了?
有人可以让我知道为什么它的段错误吗?
您没有初始化a_str
,这可以通过以下方法解决:
a_str = malloc(sizeof(*a_str));
典型的using-uninitialized-pointer(aka指针)问题。
顺便说一下,POSIX IPC API比System V IPC API更好。 看到
mq_overview (7)
消息队列概述 sem_overview (7)
信号灯概述 shm_overview (7)
共享内存概述
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.