Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

c - Do I need to keep a file open after calling mmap on it?

I have a program that maps quite a few (100's) of sizable files 10-100MB each. I need them all mapped at the same time.

At the moment I am calling open followed by mmap at the beginning of the program, followed by munmap and close at the end.

Often I have to adjust the open files limit running ulimit -n before running the program.

Question is do I actually need to keep the files open, or can I open mmap close do some large data processing then munmap when I'm finished.

The man pages of mmap do not seem terribly clear to me on this one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, at least not on Linux it's fine to close the file.

The manual page clearly states:

On the other hand, closing the file descriptor does not unmap the region.

For portability, I also checked the POSIX manual, it says the same thing (although even more clearly):

The mmap() function adds an extra reference to the file associated with the file descriptor fildes which is not removed by a subsequent close() on that file descriptor. This reference is removed when there are no more mappings to the file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...