I have an Yocto-based embedded Linux system (kernel version 5.10.48) and encounter a problem with USB flash drive removal.
I have a script that is run by udev when an USB drive is plugged or onplugged. On plugging, it should create a directory in /run/media and mount the filesystem there, and on unplugging it should unmount the filesystem and remove the mount point.
When a filesystem on USB flash drive is mounted and some process keeps a file on it opened, removing of flash drive does not cause closing of this file. So, it is impossible to unmount the filesystem and to remove its mount point directory.
For example, I have connected USB flash drive and it is detected as /dev/sdc with one FAT32 partition /dev/sdc1. So, I execute the following commands in shell:
root@host:media$ mkdir usbflash root@host:media$ mount /dev/sdc1 usbflash root@host:media$ tail -F usbflash/dir/file &  2544
and then physically remove USB flash drive. Then I try to unmount the filesystem, but I cannot do it because file is still opened:
root@host:media$ umount usbflash umount: /run/media/usbflash: target is busy. root@host:media$ lsof -p 2544 | grep file tail 2544 root 3r REG 8,33 0 1043 /run/media/usbflash/dir/file
I know that it is possible to kill the process using this file and then umount filesystem and remove its mount point, but it is not acceptable for me to kill whole process because it is an application that do some other work.
Is there any way to force the file to be closed, or to force unmount a filesystem with opened files, or to force to remove the directory that a filesystem is mounted to?