This topic seems to be old but no straight forward answer has been given. Maybe someone still looks for similar answer.
In my opinion the easiest solution is to use "ON_ABORT_COMMAND" please refer to paragraf 5.8 of below link:
linuxcnc.org/docs/devel/html/remap/remap...g_dealing_with_abort
After creation of yours "on_abort" function you must include in it any M65 (output off) to previously called M64 (output on) of an output you want to go off.
I have tested that also with user M-codes where I have one M-code switching pin on TRUE (with use of setp HAL command) so in order to reset I had another M-code that switches pin to FALSE. For all the crucial pins I need to reset back to FALSE I include proper M-command in my "on_abort" subroutine.
The only thing that can cause some issue is PAUSE command on program depending how and for what you use the pins. But that is probably different topic.