0

I have a virtual machine running and its root directory mounted to in ./vm

I have this script running on the virtual machine:

#!/usr/bin/env bash
flag=/dir/flag
echo "Listening..."
while true; do
    while [[ ! -f "$flag" ]]; do
        sleep 2
    done;
    cat "$flag"
    rm -f "$flag"
done

In the host, I have this:

#!/usr/bin/env bash
arrayA=( a b c d )
arrayB=( w x y z )
while true; do
    for i in $(seq 0 $((${#arrayA[@]} - 1 ))); do
        rm -rf ./vm/dir/*
        sync
        echo "${arrayB[i]}" > ./vm/dir/flag
        read -p "press [Enter]"
    done
done

The problem I get, is that sometimes the script in the host yells at me:

./host.sh: line ..: vm/dir/flag: No such file or directory

I don't know how to fix this. I've inserted syncs here and there, but sometimes (not always) after pressing [Enter], I get the error message, the flag is not written, and the virtual machine does nothing.

3
  • The expression [[ true ]] checks if the string true is non-empty, and returns true if so. If you want to loop forever, use while true, or more idiomatically while :
    – roaima
    Oct 9, 2021 at 9:30
  • 1
    yeah, arrayA and arrayB are filled somewhere else. I tried to strip down the script so I don't leak sensitive information.
    – onlycparra
    Oct 9, 2021 at 9:36
  • Why are you hiding the number of the line the error occurs in? That is not sensitive. It suggests that you've taken the error from a more complex case and not actually produced it with these small scripts. If the error does not actually happen with these scripts, how do you imagine we should be able to use them to figure out what is wrong? Oct 9, 2021 at 10:23

1 Answer 1

0

You seem to have a race condition. The host does 1/ expand ./vm/dir/* then 2/ rm the found files. If the vm has deleted the file between 1/ and 2/, the host indicates an error.

It shouldn’t be frequent (I was surprised it could happens so frequently given the timing : sleep, read), but it is not impossible.

Note : you don’t need to rm the flag if you want to write another content. Just directly execute echo … > ./vm/dir/flag (You may have an issue : this involves two steps : reopening the file, writing to it. The best way to avoid race conditions seems to create a flag2 file and when it is ready, rename it flag. But here using cat on an empty file doesn’t seem to harm)

Edit : is your echo or your rm which indicates an error ? Echo should only indicates an error if the directory is not there.

1
  • Hi Frédéric, the echo is the one complaining. and it happens very frequently. every other loop! My only target here is to trigger the execution of one more loop in the VM. perhaps there is a better solution than a flag file....
    – onlycparra
    Oct 9, 2021 at 9:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .