Score:0

How to avoid race condition when mounting, copying files into, and umounting images

dk flag

This script creates ten image files and copy over file(s) to them.

#!/bin/bash
# script to create multiple floppy images for installing hwp30
#+on virtualbox.

# umount image in case mounted
sudo umount /media/floppy

# create ten blank 2.88mb images.
#+then mount each image and copy over file(s).
for n in {1..10}; do
    mkfs.msdos -C "hwp30-${n}.img" 2880
    sudo mount -o loop "hwp30-${n}.img" /media/floppy
    sudo cp -v "../DISK${n}" /media/floppy

    # if first disk then copy over INSTALL.EXE
    if [[ $n -eq 1 ]]; then
        sudo cp -v ../INSTALL* /media/floppy
    fi
    
    sudo umount /media/floppy
done

# done?
if [[ $? -eq 0 ]]; then
    echo "done!"
fi

When I run this script, mounting, copying of files and umounting are out of sync; they are not done in the correct order. Umounting says 'device is busy' a few times.

After the script finishes I need to do umount command several times to umount them all(even though it is the same mount point?).

I think this is called a race condition. How to fix?

Soren A avatar
mx flag
It probably happens because there still is IO to the image while the the cache is being drained. Try adding `sync; sync` just before the line with `sudo umount /media/floppy`.. this will request a flush of unwritten data - and wait for it to happen.
Logan Lee avatar
dk flag
@SorenA thx that fixed it!
Soren A avatar
mx flag
Great, I have added it as an answer. Please accept the answer :-)
Score:2
mx flag

The problem might be that, even though the copy has finished, ther is still IO going on from cache to the mounted image.

Add sync; sync just before the line with sudo umount /media/floppy.. this will request a flush of unwritten data - and wait for it to happen.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.