LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to determine if USB flash drive is write protected (https://www.linuxquestions.org/questions/programming-9/how-to-determine-if-usb-flash-drive-is-write-protected-4175414487/)

richw42 07-02-2012 01:52 PM

How to determine if USB flash drive is write protected
 
I have an application running on an embedded computer. The user may plug in a USB flash memory and try to access it. I would like to give an error message immediately if the user tries to write to a write-protected memory, but haven't figured out how. For example, I tried
Code:

i = open(file_name, O_WRONLY | O_CREAT | O_SYNC);
        if (i < 0)
            perror("open");
        else
        {
            j = write(i, &i, 4);
            if (j != 4)
                perror("write");
            close(i);
        }

on a write protected memory, but it gave no immediate error. I can even remove the USB memory, and then fopen, fwrite, and fclose a file with no error reported to the application. The console terminal gets pelted with error messages, though.
It's an older computer, so it has Linux kernel 2.4.26 with libc 2.3.2.

Doc CPU 07-02-2012 03:39 PM

Hi there,

Quote:

Originally Posted by richw42 (Post 4717377)
I have an application running on an embedded computer. The user may plug in a USB flash memory and try to access it. I would like to give an error message immediately if the user tries to write to a write-protected memory, but haven't figured out how. For example, I tried
Code:

        i = open(file_name, O_WRONLY | O_CREAT | O_SYNC);
        if (i < 0)
            perror("open");
        else
        ...


are you sure your error criterion is correct? I know that fopen() returns a Null handle on error, and I'd assume that open() behaves the same. So your check for a negative result would never catch.
Anyway, I usually check if the result of fopen() is non-zero to proceed normally.

[X] Doc CPU

richw42 07-02-2012 04:32 PM

Quote:

are you sure your error criterion is correct?
From http://linux.die.net/man/2/open:
Quote:

open() and creat() return the new file descriptor, or -1 if an error occurred (in which case, errno is set appropriately).
I am checking the f* functions properly for non-zero.
It turns out I misremembered my own code. I'm actually writing the files to a temporary ram disk and then upon getting the "finish" command from the user, I do
Code:

sprintf(buf, "mv /tmp/tmpmidi.mid %s", file_name);
            if (system(buf))
            {
                perror("move failed");
            }

and the mv doesn't give an error (but I wish it did).
I do it this way because I don't want any flash activity while I'm recording a MIDI file.


All times are GMT -5. The time now is 06:24 AM.