0

There can be several mount points under management in linux. I want to umount them all or don't umount any. Since there are cases when linux cannot umount a device (like someone is on the mount point), I want to add a function to check all mount points and see if the devices can be umounted before I actually perform umount action.

Is there any functions like trylock to test if a device is umountable? Or if there are any function to check if any user is using the mount point like lsof?

cynkiller
  • 73
  • 9
  • 2
    you can't do this - umounting multiple drives isn't atomic... you will always have a race. Consider: Check everything is ok - find out it is; something else blocks the drive; you start unmounting; one task fails. – UKMonkey Jul 26 '18 at 10:24
  • I disagree with the latest edit: although there's no C code in the question, a solution in C seems to be the goal **and** C programmers on Linux (the combination of the tags) might be familier with [`umount()`](http://man7.org/linux/man-pages/man2/umount.2.html) and friends. -> restored tag. –  Jul 26 '18 at 11:27

3 Answers3

3

There isn't a way, AFAIK. And that's ok because your idea is flawed, it's a classic case of a TOCTOU race condition. Between checking whether umount() would succeed and actually performing it, any other process might change the outcome.

2

This answer describes it pretty well. Although the question is quite different, the answer is the same.

You can never know if an unmount in the future will succeed or not. You can find out if it would have worked (and hardly even that, because the check action is by definition not equivalent to the unmount action) when you checked it, but that information is useless a nanosecond later.

The only way this could work is if you find some way to lock the mount point, preventing it from being used by other processes, before the unmount.

klutt
  • 30,332
  • 17
  • 55
  • 95
  • *You can find out if it would have worked when you checked it* Not really. The check isn't necessarily complete - something you can't check such as SE Linux could intervene on the actual `umount`. Since the check can't be identical to the actual action, different rules can apply. So in addition to the race condition, the check can't be known to be accurate in the first place. – Andrew Henle Jul 26 '18 at 11:27
  • I'm not convinced by this example. The (classic) sequence `access(...); open(...);` is a much better one, because the problem depends on things happening outside the program, while the (also classic) `while(!eof)` error is a logical error in the flow of the program itself. –  Jul 26 '18 at 11:30
1

You can use fuser -m /mountpoint to see if any processes are using the mount point.

Note that, as Felix noted, it is very possible that some process is going to grab mount point after your check but before you issue umount.

alamar
  • 18,729
  • 4
  • 64
  • 97