Web lists-archives.com

Re: Ejecting a USB drive using Cygwin (sync)?




On 2018-01-23 04:14, Ronald Fischer wrote:
> I'm looking for a command, which would allow me from a shell script to 
> prepare the removal of a USB device (stick, external hard drive etc.). With 
> other words, after issuing the command, I should be able to physically remove
> the USB device.
> Can the `sync` command be used, for instance
>     sync -f /cygdrive/e
> assuming that the USB device is on drive E:? The man page of *sync* is a bit 
> vague in this respect. Or is there another Cygwin command which can be used
> for this purpose?

Running sync as above, and umount are always advisable.
Some ejection utilities detach the device, leaving it unusable until the device
is attached by forcing enumeration, or the system restarted.
I found the following utility works well without elevation - Windows code from
http://www.leapsecond.com/tools/eject.{c,exe}:

// eject -- Allow safe removal of USB thumb drive.
// - Command line tool to flush/dismount/eject USB drive.
// - Simpler than mouse clicking through taskbar "Safely Remove Hardware" icon.
// - Usable in batch file scripts.
// 02-Nov-2012 Tom Van Baak (tvb) www.LeapSecond.com/tools
...
// Per MSDN, follow procedure for safe removal of USB drive.
int drive_eject (char *drive)
{
    HANDLE hDev;
    // Convert vintage DOS drive letter to weird Windows object pathname.
    char path[10];
    sprintf(path, "\\\\.\\%s", drive);
    // Open (with write, but no lock) to flush pending writes.
    DEV_OPEN(path, GENERIC_READ | GENERIC_WRITE);
    FlushFileBuffers(hDev);
    CloseHandle(hDev);
    // Open (with read, and lock) to dismount and eject.
    DEV_OPEN(path, GENERIC_READ);
    DEV_IOCTL(FSCTL_LOCK_VOLUME);
    DEV_IOCTL(FSCTL_DISMOUNT_VOLUME);
    DEV_IOCTL(IOCTL_STORAGE_EJECT_MEDIA);
    DEV_IOCTL(FSCTL_UNLOCK_VOLUME);
    CloseHandle(hDev);
    return 0;
}

Cygwin does not appear to use ioctls that perform the same Windows functions
except for floppy lock volume.

-- 
Take care. Thanks, Brian Inglis, Calgary, Alberta, Canada

--
Problem reports:       http://cygwin.com/problems.html
FAQ:                   http://cygwin.com/faq/
Documentation:         http://cygwin.com/docs.html
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple