Search code examples
shellgdbshsigintopenocd

Prevent sigint from closing OpenOCD when using OpenOCD with GDB


I am trying to write a script to launch OpenOCD in the background, and then launch and instance of GDB connected to my OpenOCD server. This mostly works, except that as soon as I type the interrupt character to halt the target I am debugging my OpenOCD server exits. It appears that OpenOCD is receiving SIGINT.

I have tried to separate OpenOCD from GDB in a number of different ways, at this point my script looks like this:

#! /bin/sh

trap '' SIGINT && nohup sh -c "trap '' SIGINT & openocd -f openocd-jlink.cfg < /dev/null" &
OPENOCD_PID=$!

arm-none-eabi-gdb -ex "set architecture armv6-m" -ex "target extended-remote localhost:2331" obj/main.elf

kill $OPENOCD_PID

I'm pretty sure that this should be very overkill yet OpenOCD still exits as soon as I type the interrupt character in GDB. If I run the same commands directly from my shell (not as part of script) everything works as expected. It works even if I just run openocd -f openocd-jlink.cfg & followed by GDB, no separate shell, nohup or trapping of SIGINT is required.

I'm hoping that someone might have an idea of what I can do in my script to prevent the SIGINT in GDB from reaching OpenOCD. Maybe there is some way to daemonize entirely from shell? I have read a lot of answers here about more generic issues with SIGINT in scripts, so I have a feeling this might be something specific to OpenOCD and GDB.


Solution

  • I have managed to solve this issue by using setsid. The working version of the script is:

    #! /bin/sh
    
    setsid openocd -f openocd-jlink.cfg -l /dev/null &
    
    arm-none-eabi-gdbm" -ex "target extended-remote localhost:2331" obj/main.elf
    
    killall openoc
    

    Since I want the script to work on macOS as well as Linux and macOS does not ship with a setsid I ended up using Python to launch OpenOCD, which looks like this:

    subprocess.Popen(["openocd", "-f", "openocd-jlink.cfg", "-l", "/dev/null"], preexec_fn = os.setsid)