xdg-mime not race-condition safe
xdg-mime
doesn't seem to work properly if one tries to set values too fast/simultaneously. I'm able to reproduce the bad behavior as follows:
$ rm ~/.config/mimeapps.list
$ xdg-mime default okularApplication_epub.desktop application/epub & xdg-mime default okularApplication_pdf.desktop application/pdf
[1] 9211
mv: cannot stat '/home/jluttine/.config/mimeapps.list.new': No such file or directory
[1]+ Done xdg-mime default okularApplication_epub.desktop application/epub
$ cat ~/.config/mimeapps.list
[Default Applications]
application/pdf=okularApplication_pdf.desktop
p
Not only did it miss the other setting, but it seems that the file is corrupted.
I think xdg-mime
should definitely handle this case for at least the following reasons:
- in a desktop environment, it is possible that multiple processes are setting some values at the same time
- it is likely to happen, because it is easy to write some initialization code that runs a bunch of commands in parallel (e.g., running xdg-mime commands in i3 config)
- in general, it's just bad file IO handling if it corrupts the file like this
A simple solution
If needed, I think it would be acceptable if some of the settings would get ignored, but at least the file shouldn't get corrupted. Some pseudo-solution sketching with shell commands:
First create a random unique file safely (in the same directory):
TEMPFILE=$(mktemp ~/.config/mimeapps.list.XXXXXX)
Write the stuff into this file. Then, at the end, use mv
because it's atomic:
mv -f $TEMPFILE ~/.config/mimeapps.list
This way the file will not get corrupted, but you will might lose some settings if they are done at the same time. To handle simultaneous settings correctly, some kind of file locking (or database, please no...) would be needed.