这个代码在内存中打开一个文件缓冲区是否安全?(代码似乎工作) [英] Is this code safe for opening a buffer in memory as a file?(Code appears to work)

查看:137
本文介绍了这个代码在内存中打开一个文件缓冲区是否安全?(代码似乎工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何获取内存中缓冲区的文件描述符?

我试图强制使用 FILE 类的库在内存中使用缓冲区而不是文件。我尝试了 fmemopen ,但是,库使用 fileno ,它返回-1并导致库崩溃。所以我读了,我需要一个文件描述符,我可以使用管道命令,使一个。我不完全明白我做了什么,但我得到它的工作。但是,我不知道我做的是真的安全。所以这里是代码:

I'm trying to force a library that uses a FILE class to use a buffer in memory instead of a file. I tried fmemopen, however, the library uses fileno which returns -1 and causes the library to crash. So I read that I need a file descriptor and I could use the pipe command to make one. I don't fully understand what I did but I got it to work. However, I don't know if what I did is actually safe. So here is the code:

int fstr[2];
pipe(fstr);
write(fstr[1], src, strlen(src));
close(fstr[1]);
FILE* file = fdopen( fstr[0], "r" );

推荐答案



<解决方案

解决方案

如果你真的需要一个文件句柄,这是我能想到的一样好。

If you really need a file handle, this is as good as anything I can think of.

是管道的缓冲区大小有限。如果你的字符串大于缓冲区大小, write(...)将阻塞,直到一些数据 read )

One possible issue you may run into is that the buffer size for a pipe is limited. If your string is larger than the buffer size, the write(...) to the pipe will block until some data is read(...) from the other end.

理想情况下,你会有一个工作线程写入管道,但如果这不可能/太难,您可以通过 fcntl(fd,F_SETPIPE_SZ,...)

Ideally you would have a worker thread writing to the pipe, but if this is not possible/too hard, you can possibly adjust the pipe buffer size through fcntl(fd, F_SETPIPE_SZ, ...).

这篇关于这个代码在内存中打开一个文件缓冲区是否安全?(代码似乎工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆