spietras / beeplay

turn your crappy PC into a music player :notes:
MIT No Attribution
3 stars 0 forks source link

Possible race condition in beeplay #5

Open spietras opened 3 years ago

spietras commented 3 years ago

In beeplay from beeplaylib.sh: https://github.com/spietras/beeplayer/blob/7f39008b40355108801ab6272a3bccf63b2def9f/sh/beeplaylib.sh#L209-L217

When a note starts playing, a new subshell is run in the background (that executes note-playing function) and its PID is saved and associated with the note frequency. When that note stops playing we kill the process with PID associated with the note frequency. If everything works correctly, the subshell should be killed, which should also kill the note-playing function.

The problem is, the subshell can quit in the meantime (e.g. error happened - it's likely since the purpose of this subshell is to run user functions) and its PID can be recycled and reassigned to some new process. (I think it's like that, I need to verify that).

Can we implement some workaround for this situation?

spietras commented 3 years ago

It seems it can't be done perfectly.

But we can do something that works 99% of the time. We can save the creation of the process (alongside PID) and check if the creation time matches before killing the process. That way the only time it can go wrong is when the process dies the second it was created and some new process starts at the same time and the PID is reassigned. This is very very unlikely and someone would have to do that deliberately (and why on earth would someone mess with that just to kill some random process?).