There is an open source project doing exactly what is needed (for linux, macos and windows): killport