4

I've got a quick question, but I can't find an answer. Is it possible in linux (or in python) to see if an external usb pen drive is idling? I need to know this for a python script I'm writing. I need to rename a folder on an external usb pen drive as soon as nothing is writing to it.

edit: I know there is lsof command to list open files. 'lsof /theDir' only works half. It works OK when the process copying to the USB is still running. But when the process stops, lsof shows nothing. But the OS is still writing to the USB from its buffer.

2
  • But you will have a race: you check, the USB is idle, then you are going to rename the folder, but something goes faster and starts doing something. Then you do the rename in a non-idle state. You would need something like a volume/directory lock. Maybe unmounting the volume and mounting elsewhere in a private directory? Commented Jul 29, 2014 at 8:19
  • as far as I understand, Linux can handle this case. I just need to make a backup from a usb drive to another. I start creating a folder "incomplete files" at the destination. After that, I start copying. When the copying is done and I've got all my files, I want to rename that folder to complete+currentDate. Commented Jul 29, 2014 at 8:26

1 Answer 1

7

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

To force all buffers to be written immediately you could execute sync and wait until it returns.

Nevertheless be aware that you have a race condition here if you are not controlling the writing - after you decided that the device is idle some other process could start writing to it.

Sign up to request clarification or add additional context in comments.

7 Comments

Yeah, I've got a raspberry pi and if I use sync the transfer is about 400 KB/s, with the fat flush option enabled I get around 5 megabytes/s.
Isn't there something to check if the writing is done without using sync?
You don't need to use sync to do a backup, the OS will handle that automatically.
Updated my answer - /sys/block/<dev>/stat might be what you are looking for.
Hm, I think we have a misunderstanding here when we talk about sync. I am not talking about mounting the filesystem in sync mode. I was talking about executing the command sync. You can even call this as non-root user without sudo. Once returned you can be relatively sure that your copy operation is done. See man7.org/linux/man-pages/man1/sync.1.html
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.