通过共享内存发送整数数组

问题描述

我已经编写了生产者和使用者代码,其中从producer.c读取了从producer.c写入共享内存的字符序列。 但是,当我尝试通过共享内存从producer.c发送整数数组并从consumer.c中读取时出现了问题。

producer.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
int main(){
const int SIZE = 4096;
const char *Obj = "Shm";
int shm_fd;
void *ptr;
shm_fd = shm_open(Obj,O_CREAT | O_RDWR,0666);
ftruncate(shm_fd,SIZE);
ptr = mmap(0,SIZE,PROT_READ | PROT_WRITE,MAP_SHARED,shm_fd,0);
if (ptr == MAP_Failed)
{
     printf("Map Failed\n");
     return -1;
}
                
fgets(ptr,stdin);
printf("Producer: Writing the sequence to the shared-memory object is done! \n");
return 0;
}

消费者.c

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>

int main()
{
    const int SIZE = 4096;
    const char *Obj = "Shm";
    int shm_fd;
    void *ptr;
    shm_fd = shm_open(Obj,O_RDONLY,0666);
    if (shm_fd == -1)
    {
        printf("Shared memory Failed\n");
        exit(-1);
    }
    ptr = mmap(0,PROT_READ,0);
    if (ptr == MAP_Failed)
    {
        printf("Map Failed\n");
        exit(-1);
    }
    printf("Consumer: The output sequence is: %d",(int *)ptr);
    if (shm_unlink(Obj) == -1)
    {
        printf("Error removing the shared memory object %s\n",Obj);
        exit(-1);
    }
    return 0;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)