Linux – CHECK IF THE USB DEVICE IS IDLE, LINUX

CHECK IF THE USB DEVICE IS IDLE, LINUX… here is a solution to the problem.

CHECK IF THE USB DEVICE IS IDLE, LINUX

I have a short question but can’t find an answer.
Is it possible to see if an external USB pendrive is free in Linux (or python)?
For the python script I’m writing, I need to know this.
I need to rename the folder on my external USB pen drive as soon as nothing is written.

EDIT: I know there is a lsof command that lists open files. ‘lsof/theDir’ is only half the job. When the process copied to USB is still running, it works fine. But when the process stops, lsof shows nothing. But the operating system is still writing to USB from its buffer.

Solution

You can check if all I/O has been processed by looking at /sys/block/<dev>/stat.
The ninth column contains the amount of I/O that is currently in progress. Check https://www.kernel.org/doc/Documentation/block/stat.txt
Once this number is zero, the device should be idle.

To force all buffers to be written immediately, you can perform sync and wait until it returns.

Note, however, that if you don’t control the writes, there is a race condition here – some other process may start writing after you are sure that the device is idle.

Related Problems and Solutions