John
John

Reputation: 684

How to close a memory mapped file in C that I did not explicitly open?

How can I close a memory mapped file that I did not explicitly open using mmap in C? I'm able to see the name of the memory-mapped file using lsof and I'd like to either be able to somehow get the address and size of the file so that I may call munmap. I know that I should be able to access some memory info via /proc/self/mem/ but I'm not entirely sure how to progress from there and if this would be the safe/correct way of doing so. Thanks.

EDIT

I'm using a library that writes to a device file. What I'm trying to do is simulate this device becoming temporarily physically unavailable and having the program recover from this. A part of the device becoming available again is having it's driver reinitialized, this cannot happen with my process still maintaining a reference since the module count won't be zero and the kernel will therefore not allow unloading. I was able to identify all the file descriptors and close these, but lsof points to a shared memory location that still references the device. Since I did not explicitly open this, and the code that did so is not accessible by me, I was hoping for a way to still be able to close it.

Upvotes: 1

Views: 356

Answers (1)

Joshua
Joshua

Reputation: 43278

I would suggest the most likely safe solution is to use the exec() system call to return to a known state.

What you are asking for is how to yank the memory mapping out from some library function; which sets you up for undefined behavior in the not too distant future, probably involving the heap manager. You don't want to debug that.

OP = Heisenbug. Well that's singularly fitting.

As for the question that now appears after edit; we have here the XY problem. What would happen on device failure is not freeing the memory mapping, but most likely changing it so that all access to the region yields SIGBUS, which is a lot harder to simulate.

Upvotes: 3

Related Questions