读取存储在段中的文件并发送字节

问题描述 投票:0回答:1

我有一个文件,它存储在不同进程A的段中的结构中。现在,从进程BI需要获取此文件并将其转换为字节,以便我可以发送它或在读取其字节时发送它,这将是一个理想的方法吗?见下文:

typedef struct mysegment_struct_t {
    FILE *stream;
    size_t size;
}

所以我已经映射到该段,并且所有人都不知道如何立即获取它

size_t bytes_sent;
struct mysegment_struct_t *fileinfo = 
(struct mysegment_struct_t *)mmap(NULL,size,PROT_READ | PROT_WRITE, MAP_SHARED, fd,0);

//read stream into a byte array? (how can this be done in c)
//FILE *f  = fopen(fileinfo->stream, "w+b");   //i a bit lost here, the file is in the segment already

//send bytes
while (bytes_sent < fileinfo->size) {
  bytes_sent +=send_to_client(buffer, size); //some buffer containing bytes?
}

我是C编程的新手,但是我找不到像将内存中的文件读取到字节数组这样的内容。

谢谢

enter image description here

来自博客https://www.softprayog.in/programming/interprocess-communication-using-posix-shared-memory-in-linux

必须有一种方法可以使用共享内存在进程之间共享文件。

c file shared-memory
1个回答
3
投票

您根本无法做到这一点。指针stream指向仅存在于进程A的内存中并且不在共享内存区域中的对象(即使它们存在,它们通常也不会映射到相同的地址)。您将不得不设计其他东西。

一种可能是通过Unix域套接字发送文件描述符,请参见Portable way to pass file descriptor between different processes。但是,可能值得退后一步来思考一下,为什么首先要在进程之间传递一个打开的文件,以及是否有更好的方法来实现总体目标。

© www.soinside.com 2019 - 2024. All rights reserved.