读取存储在段中的文件并发送字节
Read file stored in segment and send bytes
我有一个文件存储在来自不同进程 A 的段中的结构中。现在我需要从进程 B 获取此文件并将其转换为字节,以便我可以发送它或在读取其字节时发送它,这样做的理想方式是什么?见下文:
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 编程的新手,但我找不到诸如将内存中的文件读入字节数组之类的东西。
谢谢
来自博客 https://www.softprayog.in/programming/interprocess-communication-using-posix-shared-memory-in-linux
必须有一种方法可以使用共享内存在进程之间共享文件。
你根本做不到。指针 stream
指向的对象只存在于进程 A 的内存中,不在共享内存区域中(即使存在,它们通常也不会映射到同一地址)。你将不得不设计别的东西。
一种可能性是通过 Unix 域套接字发送文件描述符,请参阅 Portable way to pass file descriptor between different processes。但是,可能值得退一步思考一下为什么您首先要在进程之间传递一个打开的文件,以及是否有更好的方法来实现您的总体目标。
我有一个文件存储在来自不同进程 A 的段中的结构中。现在我需要从进程 B 获取此文件并将其转换为字节,以便我可以发送它或在读取其字节时发送它,这样做的理想方式是什么?见下文:
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 编程的新手,但我找不到诸如将内存中的文件读入字节数组之类的东西。
谢谢
来自博客 https://www.softprayog.in/programming/interprocess-communication-using-posix-shared-memory-in-linux
必须有一种方法可以使用共享内存在进程之间共享文件。
你根本做不到。指针 stream
指向的对象只存在于进程 A 的内存中,不在共享内存区域中(即使存在,它们通常也不会映射到同一地址)。你将不得不设计别的东西。
一种可能性是通过 Unix 域套接字发送文件描述符,请参阅 Portable way to pass file descriptor between different processes。但是,可能值得退一步思考一下为什么您首先要在进程之间传递一个打开的文件,以及是否有更好的方法来实现您的总体目标。