Add a test to cover the behavior described in https://github.com/bitcoin/bitcoin/issues/2039, in preparation for fixing it.
The functional test was massage to be slightly less bad code: fewer levels of `try-except` wrapping, deduplication of the platform specific code (only the command name changes based on the OS)
This is a backport of [[https://github.com/bitcoin/bitcoin/pull/28545 | core#28545]], [[https://github.com/bitcoin/bitcoin/pull/27850 | core#27850]] and [[https://github.com/bitcoin/bitcoin/pull/28660 | core#28660]]
Depends on D18969